199. Binary Tree Right Side View

来源:互联网 发布:中国经济数据统计网 编辑:程序博客网 时间:2024/06/15 14:37

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.

For example:
Given the following binary tree,

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

You should return [1, 3, 4].

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.


Java Code:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> rightSideView(TreeNode root) {        Queue<TreeNode> queue = new LinkedList<>();        List<Integer> result = new ArrayList<>();        if (null == root) {            return result;        }        queue.add(root);                while (!queue.isEmpty()) {            int qSize = queue.size();                        for (int i = 0; i < qSize; i++) {                TreeNode node = queue.poll();                if (node.left != null) {                    queue.add(node.left);                }                                if (node.right != null) {                    queue.add(node.right);                }                                if (i == qSize - 1) {                    result.add(node.val);                }            }        }                return result;    }}


0 0
原创粉丝点击