LeetCode 199. Binary Tree Right Side View

问题描述

  • Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
  • Example :
    这里写图片描述

  • 地址

问题分析

  • 想象你站在一棵树的右边,从上到下,返回你能看到的所有节点
  • 两种思路:
    • BFS,类似于 LeetCode 102. Binary Tree Level Order Traversal 只要将每一层最右边的节点值加入到结果集中
    • DFS,简直就是给大佬跪了,神奇的脑回路。
      一种“根右左”的dfs遍历方式,保证得到是当前层最右边的节点,并且只有当前节点的深度depth等于结果集大小 res.size(),说明这是遇到的当前层的第一个节点。则添加进结果集。

代码实现

  • BFS
    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) {
            return new ArrayList<Integer>();
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        ArrayList<Integer> res = new ArrayList<>();
        TreeNode popNode = null;
        while (! queue.isEmpty()) {
            int levelSize = queue.size();
            //当前层前 levelSize - 1 个元素
            for (int i = 0; i < levelSize - 1; i++) {
                popNode = queue.remove();
                if (popNode.left != null) {
                    queue.add(popNode.left);
                }
                if (popNode.right != null) {
                    queue.add(popNode.right);
                }
            }
            //当前层最后一个元素,加入结果集中
            popNode = queue.pop();
            if (popNode.left != null) {
                queue.add(popNode.left);
            }
            if (popNode.right != null) {
                queue.add(popNode.right);
            }
            res.add(popNode.val);
        }
        return res;
    }
  • DFS
    public List<Integer> rightSideView(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        rightSideView(root, 0, res);
        return res;
    }

    public void rightSideView(TreeNode root, int depth, List<Integer> res) {
        if (root == null) {
            return;
        }
        if (depth == res.size()) {
            //如果当前节点的深度等于res大小,说明depth层节点尚未加入,所以应当加入该节点
            res.add(root.val);
        }
        //先右后左,能保证当前层加入的是最右边的节点
        //(因为当前层一旦加入,res大小便会超过depth,那么该层其他节点便不会被加入)
        //同样,可以保证,当左子树比右子树深时,还能不遗漏左子树的节点。
        rightSideView(root.right, depth + 1, res);
        rightSideView(root.left, depth + 1, res);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值