首页 > 其他 > 详细

Binary Tree Right Side View

时间:2015-09-01 07:59:52      阅读:164      评论:0      收藏:0      [点我收藏+]

 

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

Binary Tree Right Side View

原文:http://www.cnblogs.com/hygeia/p/4774753.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!