二叉搜索树的中序遍历是有序的
对于二叉搜索树的题记住这个特点就好
模板
class Solution {
int res=Integer.MAX_VALUE;
int last;
boolean con=true;
public int getMinimumDifference(TreeNode root) {
f(root);
return res;
}
public void f(TreeNode root){
if(root==null) return;
f(root.left);
if(con){
last=root.val;
con=false;
}
else{
//逻辑
last=root.val;
}
f(root.right);
}
}
验证二叉搜索树(LeetCode98)
中序遍历不是递增的,就是错误的
class Solution {
boolean res=true;
int last=-1000;
public boolean isValidBST(TreeNode root) {
f(root);
return res;
}
public void f(TreeNode root){
if(root==null) return;
f(root.left);
if(last==-1000) last=root.val;
else{
if(last>=root.val) res=false;
}
last=root.val;
f(root.right);
}
}
二叉树的最小绝对值差(LeetCode530)
class Solution {
int res=Integer.MAX_VALUE;
int last;
boolean con=true;
public int getMinimumDifference(TreeNode root) {
f(root);
return res;
}
public void f(TreeNode root){
if(root==null) return;
f(root.left);
if(con){
last=root.val;
con=false;
}
else{
res=Math.min(root.val-last,res);
last=root.val;
}
f(root.right);
}
}
二叉搜索树中的众数(LeetCode501)
不要嫌弃代码冗长,最开始写代码最重要的是固定好解题思路。
class Solution {
boolean con=true;
int maxnum=0,num=0,last=0;
List<Integer> res=new ArrayList<>();
public int[] findMode(TreeNode root) {
f(root);
return res.stream().mapToInt(Integer::intValue).toArray();
}
public void f(TreeNode root){
if(root==null) return;
f(root.left);
if(con||last==root.val){
last=root.val;
con=false;
num++;
}
else{
num=1;
last=root.val;
}
if(num>maxnum){
res.clear();
res.add(root.val);
maxnum=num;
}
else if(num==maxnum){
res.add(root.val);
}
f(root.right);
}
}