199. Binary Tree Right Side View | 从右边看二叉树得到的集合

来源:互联网 发布:国语电影排行榜 知乎 编辑:程序博客网 时间:2024/06/11 06:58

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.

Subscribe to see which companies asked this question.


思路:广度优先遍历,用队列层次遍历,并记录每层的个数,当遍历到最后一个的时候就添加到结果集合中,最后返回结果。

/** * 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) {List<Integer> list = new ArrayList<>();if (root == null) {return list;}LinkedList<TreeNode> queue = new LinkedList<>();queue.push(root);int next = 0, num = 1;while (!queue.isEmpty()) {TreeNode treeNode = queue.poll();num--;if (treeNode.left != null) {queue.addLast(treeNode.left);next++;}if (treeNode.right != null) {queue.addLast(treeNode.right);next++;}if (num == 0) {list.add(treeNode.val);num = next;next = 0;}}return list;}}


0 0
原创粉丝点击