• 欢迎光临~

# 掌握二叉搜索树的双指针 + 公共祖先加深对后序遍历和递归的理解

### 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);
for (int i = 0; i < arr.size(); i++) {
}
}

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;
} else if (count == ModeLength) {
}
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;
}
}

``````