题意: 对于一棵二叉树,站在右边观看,输出能够看到的数字,分析一下就是输出每一层的最右边的数字
思路: 先把根节点加入,然后依次对于剩下的节点,先判断右孩子是否存在,然后判断左孩子是否存在,由于是求每一层的最右边的数字,所以加一个标识符表示当前已经到大第几层,如果该层已经有了节点,那么剩余的(左兄弟)加入失败
代码:
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if(root == null){
return ans;
}
ans.add(root.val);
if(root.right != null){
DFS(ans, root.right, 1);
}
if(root.left != null){
DFS(ans, root.left, 1);
}
return ans;
}
public void DFS(List<Integer> ans, TreeNode parent, int floor){
if(floor == ans.size()){
ans.add(parent.val);
}
if(parent.right != null){
DFS(ans, parent.right, floor + 1);
}
if(parent.left != null){
DFS(ans, parent.left, floor + 1);
}
}