第六章 二叉树part07
大纲
● 530.二叉搜索树的最小绝对差
● 501.二叉搜索树中的众数
● 236. 二叉树的最近公共祖先
leetcode 530
二叉搜索树的最小绝对差
代码
class Solution {
int min = Integer.MAX_VALUE, pre = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
getMinimumDifference(root.left);
int dif = Math.abs(pre - root.val);
min = dif > min ? min : dif;
pre = root.val;
getMinimumDifference(root.right);
return min;
}
}
leetcode 501
二叉搜索树中的众数
代码
class Solution {
List<Integer> res = new ArrayList<>();
int count = 0, maxCount = 0, pre = Integer.MAX_VALUE;
public int[] findMode(TreeNode root) {
inorder(root);
int[] resNum = new int[res.size()];
for (int i = 0; i < res.size(); i++) resNum[i] = res.get(i);
return resNum;
}
public void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
if (pre == Integer.MAX_VALUE) count = 1;
else if (pre == node.val) count++;
else count = 1;
pre = node.val;
if (count == maxCount) res.add(node.val);
else if (count > maxCount) {
maxCount = count;
res.clear();
res.add(node.val);
}
inorder(node.right);
}
}
leetcode 236
二叉树的最近公共祖先
代码
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == root || q == root) 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;
}
}