描述:
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; Listlist=new ArrayList(); Listtemp=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; }
結果: