530.二叉搜索树的最小绝对差
int min = Integer.MAX_VALUE;
TreeNode pre;
/**
* <A href="https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/">530. 二叉搜索树的最小绝对差</A>
*/
public int getMinimumDifference1(TreeNode root) {
if (root == null) {
return 0;
}
travel1(root);
return min;
}
public void travel1(TreeNode cur) {
if (cur == null) {
return;
}
travel1(cur.left);
if (pre != null) {
min = Math.min(min, (cur.val - pre.val));
}
pre = cur;
travel1(cur.right);
}
501.二叉搜索树中的众数
/**
* <A href="https://leetcode.cn/problems/find-mode-in-binary-search-tree/">501. 二叉搜索树中的众数</A>
*/
int ModeLength = 0;
int count = 0;
List<Integer> arr;
TreeNode pre;
public int[] findMode(TreeNode root) {
arr = new ArrayList<>();
travel2(root);
int[] answer = new int[arr.size()];
for (int i = 0; i < arr.size(); i++) {
answer[i] = arr.get(i);
}
return answer;
}
public void travel2(TreeNode cur) {
if (cur == null) {
return;
}
travel2(cur.left);
if (pre == null || pre.val != cur.val) {
count = 1;
} else {
count++;
}
pre = cur;
if (count > ModeLength) {
arr.clear();
ModeLength = count;
arr.add(cur.val);
} else if (count == ModeLength) {
arr.add(cur.val);
}
travel2(cur.right);
}
236. 二叉树的最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if(root.val == p.val || root.val == q.val){
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left != null && right != null){
return root;
}else if(left==null){
return right;
}else{
return left;
}
}
标签:遍历,TreeNode,cur,val,后序,二叉,return,null,root
From: https://www.cnblogs.com/Chain-Tian/p/17017683.html