描述:
?
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 ListrightSideView(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; }
?
结果:
