标签:
Given a binary tree, imagine yourself standing on the rightside 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]
.
1 public List<Integer> rightSideView(TreeNode root) { 2 List<Integer> res = new ArrayList<Integer>(); // save the result to this variable 3 if (root == null) return res; 4 5 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 6 queue.add(root); 7 int curLevCnt = 1; 8 int nextLevCnt = 0; 9 int levelres = 0; 10 11 while(!queue.isEmpty()){ 12 TreeNode cur = queue.poll(); 13 curLevCnt--; 14 //levelres.add(cur.val); 15 16 if(cur.left != null){ 17 queue.add(cur.left); 18 nextLevCnt++; 19 } 20 if(cur.right != null){ 21 queue.add(cur.right); 22 nextLevCnt++; 23 } 24 25 if(curLevCnt == 0){ 26 curLevCnt = nextLevCnt; 27 nextLevCnt = 0; 28 levelres = cur.val; 29 res.add(cur.val); 30 //levelres =new int; 31 } 32 } 33 return res; 34 35 }
very similar with Binary Tree Level Order Traverse
http://www.cnblogs.com/hygeia/p/4704027.html
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4774753.html