一、[530]二叉搜索树的最小绝对差
重点:双指针
class Solution {int minRes=Integer.MAX_VALUE;TreeNode pre=null;public int getMinimumDifference(TreeNode root) {traversal(root);return minRes;}void traversal(TreeNode cur){//中序遍历if(cur==null){return;}traversal(cur.left);if(pre!=null){int tmp= cur.val- pre.val;minRes=Math.min(minRes,tmp);}pre=cur;traversal(cur.right);}
}
二、[501]二叉搜索树中的众数
class Solution {List<Integer> res=new ArrayList<>();int count=0;int maxCount=0;TreeNode pre=null;public int[] findMode(TreeNode root) {traversal(root);int[] result = new int[res.size()];for (int i = 0; i < res.size(); i++) {result[i] = res.get(i);}return result;}void traversal(TreeNode root){if(root==null){return;}traversal(root.left);if(pre!=null && pre.val==root.val){count++;}else{count=1;}pre=root;if(count>maxCount){//注意!!!!res.clear();res.add(root.val);maxCount=count;}else if(count==maxCount){res.add(root.val);}traversal(root.right);}
}
三、[236]二叉树的最近公共祖先
注意:节点相等,而不是值相等
class Solution {//后序遍历public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root==null){return null;}if(root==p||root==q){return root;}TreeNode left = lowestCommonAncestor(root.left, p, q);TreeNode right = lowestCommonAncestor(root.right, p, q);if (left==null&&right==null) {return null;}else if(left==null&&right!=null){return right;} else if (left!=null&&right==null) {return left;}else if(left!=null&&right!=null){return root;}return root;}
}