● 530.二叉搜索树的最小绝对差
先按照直白方式写:将二叉搜索树中序遍历转换为有序数组,然后求最小的相邻元素的差值。
class Solution {
private List<Integer> list = new ArrayList<>();
public int getMinimumDifference(TreeNode root) {
traversal(root);
int min =Integer.MAX_VALUE;
for(int i = 1;i<list.size();i++){
min = Math.min(min,list.get(i)-list.get(i-1));
}
return min;
}
private void traversal(TreeNode root){
if(root == null){
return;
}
traversal(root.left);
list.add(root.val);
traversal(root.right);
}
}
双指针法
对于递归来说,哪个遍历,中序遍历举例,那么递归函数出现在左和右,具体操作出现在中
class Solution {
private int res = Integer.MAX_VALUE;
private TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
traversal(root);
return res;
}
private void traversal(TreeNode cur){
if(cur==null){
return;
}
traversal(cur.left);
if(pre!=null){
res = Math.min(res,cur.val-pre.val);
}
pre = cur;
traversal(cur.right);
}
}
● 501.二叉搜索树中的众数
双指针写法
学到如何将List<Integer>转化为int[]的方法,利用stream流。
ArrayList 转换成 int[ ] 数组..._arraylist转int[]-CSDN博客
count计数计的是cur所指向数字的频次
class Solution {
private TreeNode pre = null;
private int count = 0;
private int maxcount = 0;
List<Integer> res = new ArrayList<>();
public int[] findMode(TreeNode root) {
traversal(root);
return res.stream().mapToInt(Integer::valueOf).toArray();//将List<Integer> 转化为int[];
}
private void traversal(TreeNode cur){
if(cur == null) return;
traversal(cur.left);
if(pre==null) count=1;
else if(pre.val == cur.val) count++;//这一部分处理count计数
else count=1;
pre=cur;
if(count==maxcount) res.add(cur.val);
if(count>maxcount){
maxcount = count;//这一部分处理res,放答案
res.clear();
res.add(cur.val);
}
traversal(cur.right);
return;
}
}
● 236. 二叉树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==p||root==q||root==null) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left!=null&&right!=null) return root;
if(left!=null&&right==null) return left;
if(left==null&&right!=null) return right;
return null;
}
}