leetocde_Binary Tree Right Side View

2015-07-20 17:05:59 ? 作者: ? 浏览: 2

描述:

?

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].

思路:

按层序遍历的思路,每次只保存该层的最后一个元素即可。

代码:

?

public List
  
    rightSideView(TreeNode root) {
        List
   
    listReturn=new ArrayList
    
     (); if(root==null) return listReturn; List
     
      list=new ArrayList
      
       (); List
       
        temp=new ArrayList
        
         (); list.add(root); TreeNode node=null; listReturn.add(root.val); while(list.size()!=0) { for(int i=0;i
         
          0) listReturn.add(temp.get(temp.size()-1).val); list.clear(); list=temp; temp=new ArrayList
          
           (); } return listReturn; }
          
         
        
       
      
     
    
   
  

?

结果:

\

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: