双非本科准备秋招(23.1)—— 力扣二叉搜索树

 1、501. 二叉搜索树中的众数

        中序遍历得到有序数组和最高频次,然后再次遍历有序数组。

        可以改进一下,只遍历一次:每次更新最大值的时候,顺便清空数组,这样最后数组里一定都是最高频次的元素了。

class Solution {
    List<Integer> list = new ArrayList<>();
    int cnt = 1;
    TreeNode pre = null;
    int maxValue = 0;

    public int[] findMode(TreeNode root) {
        inOrder(root);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }

    void inOrder(TreeNode root){
        if(root == null) return ;
        inOrder(root.left);

        if(pre != null){
            if(pre.val == root.val){
                cnt++;
            }
            else{
                //不相等,说明遇到新元素
                cnt = 1;

            }
        }
        pre = root;
        // maxValue = Math.max(maxValue, cnt);
        if(cnt == maxValue){
            list.add(root.val);
        }
        else if(cnt > maxValue){
            maxValue = cnt;
            list.clear();
            list.add(root.val);
        }

        inOrder(root.right);
    }
}

2、236. 二叉树的最近公共祖先

        核心思想就是层层返回拥有p或者q的节点。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return postOrder(root, p, q);
    }
    TreeNode postOrder(TreeNode root, TreeNode p, TreeNode q){
        if(root == null) return root;
        if(root == p || root == q) return root;

        TreeNode left = postOrder(root.left, p, q);
        TreeNode right = postOrder(root.right, p, q);

        if(left != null && right != null) return root;
        else if(left == null && right != null) return right;
        else if(left != null && right == null) return left;
        else return null; 
    }
}

3、235. 二叉搜索树的最近公共祖先

        根据二叉搜索树的特点,使用前序遍历,只要当前节点的值在p、q之间,就代表当前节点是二叉搜索树的最近公共祖先。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        if(p.val > q.val){
            TreeNode x = q;
            q = p;
            p = x;
        }

        while(root != null || !stack.isEmpty()){
            if(root != null){
                if(root.val >= p.val && root.val <= q.val){
                    return root;
                }
                stack.push(root);
                root = root.left;
            }
            else{
                TreeNode t = stack.pop();
                root = t.right;
            }
        }
        return null;
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值