二叉搜索树:
一大特点是中序遍历为单调递增。
530. 二叉搜索树的最小绝对差
class Solution {
int Min = 2147483647;
TreeNode pre;
public int getMinimumDifference(TreeNode root) {
Compose(root);
return Min;
}
public void Compose(TreeNode root){
if(root == null)
return;
Compose(root.left);
if(pre != null)
Min = Math.min(Min, root.val - pre.val);
pre = root;
Compose(root.right);
}
}
501. 二叉搜索树中的众数
class Solution {
List<Integer> list = new ArrayList<>();
TreeNode pre = null;
int count = 0;
int mostNum = 0;
public int[] findMode(TreeNode root) {
traversal(root);
//因为要输出int数组,所以需要一下循环,但是正常情况可以使用:toArray();
int[] a = new int[list.size()];
for(int i = 0; i < list.size(); i++){
a[i] = list.get(i);
}
return a;
}
public void traversal(TreeNode root){
//跳出条件
if(root == null)
return;
traversal(root.left);
//中间节点的处理:
//往往都要考虑pre为null的情况,因为null无法进行任何操作,会出异常
if(pre == null)
count = 1;
else if(pre.val == root.val){
count++;
}else
count = 1;
if(count == mostNum)
list.add(root.val);
if(count > mostNum){
mostNum = count;
list.clear();
list.add(root.val);
}
//一切完成之后,在遍历右节点之前,将当前节点传给前一个节点。
pre = root;
traversal(root.right);
}
}









