每日一题leetcode199-二叉树的右视图

二叉树的右视图

https://leetcode-cn.com/problems/binary-tree-right-side-view/

思路:

优先从左边dfs,每次直接覆盖就好了。

代码:

class Solution {
public List rightSideView(TreeNode root) {
        List resList = new LinkedList<>();
        findRight(root, resList, 0);
        return resList;
    }

    private void findRight(TreeNode node, List 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);
        }
        //优先向左深度遍历
        if(node.left != null){
            findRight(node.left, list, depth+1);
        }
        if(node.right != null){
            findRight(node.right , list, depth+1);
        }
    }
}

你可能感兴趣的:(每日一题leetcode199-二叉树的右视图)