代码随想录算法训练营第21天|530. 二叉搜索树的最小绝对差,501. 二叉搜索树中的众数,236. 二叉树的最近公共祖先

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;
          
    }
}
  • 二叉树什么时候需要返回值什么时候不需要返回值

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值