码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Right Side View

时间:2015-09-01 08:01:08      阅读:175      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!