方法一:BFS
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list=new ArrayList<>();
if(root==null) return list;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int count=queue.size();
for(int i=0;i<count;i++){
TreeNode node=queue.poll();
if(i==count-1){
list.add(node.val);
}
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
}
}
return list;
}
方法二:DFS
思路:先序遍历:根结点->左子树->右子树 本题采用根结点->右子树->左子树
这样会把右结点全都遍历完,在遍历过程中记录层数,如果res.size()和层数相等,说明这一层还没有记录到res中,反之,说明这一层的最右结点已经在res中。
List<Integer> res=new LinkedList<>();
public List<Integer> rightSideView(TreeNode root) {
dfs(root,0);
return res;
}
public void dfs(TreeNode root,int depth){
if(root==null) return;
if(res.size()==depth) {
res.add(root.val);
}
depth++;
dfs(root.right,depth);
dfs(root.left,depth);
}