原题链接在这里:https://leetcode.com/problems/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.
For example:
Given the following binary tree,
1 <--- / 2 3 <--- 5 4 <---
You should return [1, 3, 4]
.
题解:
与Binary Tree Level Order Traversal相似,通过BFS一层一层扫树,这里是仅添加最右面的一个点,就是curCount = 1 的时候.
Note: 当curCount == 0 时, curCount = nextCount, 不要忘记把nextCount归0.
Time Complexity: O(n). n是tree的node总数.
Space: O(n), que的大小.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> rightSideView(TreeNode root) { 12 List<Integer> res = new ArrayList<Integer>(); 13 if(root == null){ 14 return res; 15 } 16 17 LinkedList<TreeNode> que = new LinkedList<TreeNode>(); 18 que.add(root); 19 int curCount = 1; 20 int nextCount = 0; 21 while(!que.isEmpty()){ 22 TreeNode cur = que.poll(); 23 curCount--; 24 25 if(cur.left != null){ 26 que.add(cur.left); 27 nextCount++; 28 } 29 if(cur.right != null){ 30 que.add(cur.right); 31 nextCount++; 32 } 33 34 if(curCount == 0){ 35 res.add(cur.val); 36 curCount = nextCount; 37 nextCount = 0; 38 } 39 } 40 41 return res; 42 } 43 }