二叉樹的右視圖
https://leetcode-cn.com/problems/binary-tree-right-side-view/
思路:
優(yōu)先從左邊dfs,每次直接覆蓋就好了。
代碼:
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> resList = new LinkedList<>();
findRight(root, resList, 0);
return resList;
}
private void findRight(TreeNode node, List<Integer> list, int depth){
if(node == null){return;}
if(depth+1 > list.size()){
list.add(node.val);
}else{
list.remove(depth);
list.add(depth,node.val);
}
//優(yōu)先向左深度遍歷
if(node.left != null){
findRight(node.left, list, depth+1);
}
if(node.right != null){
findRight(node.right , list, depth+1);
}
}
}