530. 二叉搜索树的最小绝对差
通过中序遍历得到有序序列。然后利用双指针快速解题
class Solution {
int res = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
traversal(root);
return res;
}
public void traversal(TreeNode cur){
if(cur == null) return;
// 左
traversal(cur.left);
// 中
if(pre != null){
res = Math.min(res, Math.abs(pre.val - cur.val));
}
pre = cur; //记录前一个节点
// 右
traversal(cur.right);
}
}
501. 二叉搜索树中的众数
中序遍历处理二叉搜索树(出来是有序数列)
class Solution {
List<Integer> res = new ArrayList<>();
int maxcount = 0;
int count = 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;
}
public void traversal(TreeNode cur){
if(cur == null) return;
// 左
traversal(cur.left);
// 第一种情况,如果pre为空或者pre和cur数值不相等则count = 1;
// 第二种情况,当发现数值相等的节点时count++;
if(pre == null || pre.val != cur.val) count = 1;
else if(pre.val == cur.val) count++;
// 即时更新结果集
if(count == maxcount) {
res.add(cur.val);
} else if(count > maxcount){
maxcount = count;
res.clear();
res.add(cur.val);
}
pre = cur;
// 右
traversal(cur.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 root;
if(left != null && right == null) return left;
else if(right != null && left == null) return right;
else return null;
}
}
- 二叉树什么时候需要返回值什么时候不需要返回值