题目
思路
- 之前做过一道分清楚二叉树遍历的每层的题,这道题应该在那个的基础上,把每层最右的节点加入返回的列表就好。写了一下直接AC。看了一下题解属于广度优先遍历的解法,那么再看一下深度优先遍历的解法。
代码(BFS)
public List rightSideView(TreeNode root) {
List ans = new ArrayList<>();
//创建队列
Queue que = new ArrayDeque<>();
que.add(root);
while(!que.isEmpty()){
//当前层的长度
int size = que.size();
//每层一起出
for(int i=0;i
TreeNode temp = que.remove();
if(i== size-1){ //最后一个的话 需要加进ans
ans.add(temp.val);
}
//入它左右孩子
if(temp.left!=null) que.add(temp.left);
if(temp.right!=null) que.add(temp.right);
}
}
//返回ans
return ans;
}
代码(DFS)
List ans = new ArrayList<>();
public List rightSideView(TreeNode root) {
//根右左进行遍历 可以保证最先遍历到右边的节点
//需要维护一个depth用以判断是否加入ans
DFS(root,0);
return ans;
}
public void DFS(TreeNode root,int depth){
if(root==null) return;
//如果当前depth和ans相等 说明第depth层的节点还没有加入ans
//而作为根右左的遍历 此时的root一定是最右边且应该加入的节点
if(depth==ans.size()) ans.add(root.val);
//继续遍历
DFS(root.right,depth+1);
DFS(root.left,depth+1);
}