描述:
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<Integer> rightSideView(TreeNode root) { List<Integer>listReturn=new ArrayList<Integer>(); if(root==null) return listReturn; List<TreeNode>list=new ArrayList<TreeNode>(); List<TreeNode>temp=new ArrayList<TreeNode>(); list.add(root); TreeNode node=null; listReturn.add(root.val); while(list.size()!=0) { for(int i=0;i<list.size();i++) { node=list.get(i); if(node.left!=null) temp.add(node.left); if(node.right!=null) temp.add(node.right); } if(temp.size()>0) listReturn.add(temp.get(temp.size()-1).val); list.clear(); list=temp; temp=new ArrayList<TreeNode>(); } return listReturn; }
结果:
leetocde_Binary Tree Right Side View
原文地址:http://blog.csdn.net/mnmlist/article/details/44945941