首页 > 其他 > 详细

0199. Binary Tree Right Side View (M)

时间:2021-02-06 18:38:24      阅读:25      评论:0      收藏:0      [点我收藏+]

Binary Tree Right Side View (M)

题目

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:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   2     3         <---
 \       5     4       <---

题意

站在一个二叉树的右边向左看,求从上到下能看到的所有元素。

思路

相当于取每一行的最右元素,层序遍历即可。


代码实现

Java

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();

        if (root != null) {
            q.offer(root);
        }

        while (!q.isEmpty()) {
            int size = q.size();
            TreeNode cur = null;
            while (size > 0) {
                cur = q.poll();
                if (cur.left != null) q.offer(cur.left);
                if (cur.right != null) q.offer(cur.right);
                size--;
            }
            ans.add(cur.val);
        }

        return ans;
    }
}

0199. Binary Tree Right Side View (M)

原文:https://www.cnblogs.com/mapoos/p/14381925.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!