530.二叉搜索树的最小绝对差
题目链接: 530.二叉搜索树的最小绝对差
解题思路:因为二叉搜索树是有序的,其最小绝对差必然产生于相邻节点差的绝对值中
代码如下:
class Solution {
TreeNode pre;// 记录上一个遍历的结点
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root==null)return 0;
traversal(root);
return result;
}
public void traversal(TreeNode root){
if(root==null)return;
//左
traversal(root.left);
//中
if(pre!=null){
result = Math.min(result,root.val-pre.val);
}
pre = root;
//右
traversal(root.right);
}
}
501. 二叉搜索树中的众数
题目链接:501.二叉搜索树中的众数
用map存储和当前最大数出现一样的次数 如果最大值更新则清空map,最终map中存储的就是众数
代码如下:
class Solution {
public int[] findMode(TreeNode root) {
int count = 0;
int maxCount = 0;
TreeNode pre = null;
LinkedList<Integer> res = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null)
stack.add(root);
while(!stack.isEmpty()){
TreeNode curr = stack.peek();
if(curr != null){
stack.pop();
if(curr.right != null)
stack.add(curr.right);
stack.add(curr);
stack.add(null);
if(curr.left != null)
stack.add(curr.left);
}else{
stack.pop();
TreeNode temp = stack.pop();
if(pre == null)
count = 1;
else if(pre != null && pre.val == temp.val)
count++;
else
count = 1;
pre = temp;
if(count == maxCount)
res.add(temp.val);
if(count > maxCount){
maxCount = count;
res.clear();
res.add(temp.val);
}
}
}
int[] result = new int[res.size()];
int i = 0;
for (int x : res){
result[i] = x;
i++;
}
return result;
}
}
236 最近公共祖先
解题思路:递归判断当前子树是否含有p或者q
找到最近公共祖先的两种情况:
**情况1:**如果找到一个节点,发现左子树出现结点p,右子树出现节点q,或者 左子树出现结点q,右子树出现节点p,那么该节点就是节点p和q的最近公共祖先。
**情况2:**节点本身p(q),它拥有一个子孙节点q§
解题思路:递归判断当前子树是否含有p或者q
使用后序遍历 如果找到最近公共祖先则不断想根结点返回
代码如下:
/**
此问题有三种情况
1) p和q其中有一个正好是root,直接返回root就行
2) p和q分别在root的不同子树,直接返回root就行
3) p和q在root的同一侧,且root不等于p或者q的任何一个,那么就找p和q在的那一侧子树
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null){
return null;//当前结点为空 返回null 表明当前子树没有p和q的公共祖先
}
|| root == p || root == q) { // 如果当前结点为p或q 返回结点
return root;
}
// 后序遍历
TreeNode left = lowestCommonAncestor(root.left, p, q);//左子树中是否有p或q
TreeNode right = lowestCommonAncestor(root.right, p, q);//右子树中是否有p或q
if(left == null && right == null) { // 若未找到节点 p 或 q
return null;
}else if(left == null && right != null) { // 若找到一个节点 上传左边
return right;
}else if(left != null && right == null) { // 若找到一个节点 上传左边
return left;
}else { // 若找到两个节点 上传根节点
return root;
}
}
}