问题描述
给定一个二叉树,要求按照从上到下的顺序输出其右视图的节点值。题目链接:**点我**
样例输入输出
输入: [1,2,3,null,5,null,4]
输出:[1, 3, 4]
说明:
1 <—-
/ \
2 3 <—-
\ \
5 4 <—-
输入:[1,null,3]
输出:[1,3]
问题解法
此题就是求出树的每一层中最后节点。使用广搜的做法,从上到下依次输出每层的最后一个节点值即可。代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new LinkedList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int nextCount = 1; while (!queue.isEmpty()) { TreeNode current = null; int count = 0; for (int i = nextCount; i > 0; i--) { current = queue.poll(); if (current.left != null) { queue.add(current.left); count++; }
if (current.right != null) { queue.add(current.right); count++; } } nextCount = count; if (current != null) { result.add(current.val); } } return result; } }
|