larscheng / algo

0 stars 0 forks source link

【Check 53】2024-04-16 - 199. 二叉树的右视图 #155

Open larscheng opened 2 months ago

larscheng commented 2 months ago

199. 二叉树的右视图

larscheng commented 2 months ago

思路

class Solution { //递归dfs public List rightSideView(TreeNode root) { List res = new ArrayList<>(); if (root==null){ return res; } helper(root,res,0); return res; }

private void helper(TreeNode root, List<Integer> res, int depth) {
    if (root==null){
        return;
    }
    if (res.size()<=depth){
        res.add(root.val);
    }else {
        res.set(depth,root.val);
    }

    helper(root.left, res, depth + 1);
    helper(root.right, res, depth + 1);
}

}


```java
    class Solution1 {

        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if (root==null){
                return res;
            }
            Deque<TreeNode> queue = new ArrayDeque<>();
            queue.add(root);
            while (!queue.isEmpty()){
                int size = queue.size();
                for (int i = 0; i < size ; i++) {
                    TreeNode node = queue.poll();
                    //队列先进先出,收集最后出来的
                    if (node.left!=null){
                        queue.add(node.left);
                    }
                    if (node.right!=null){
                        queue.add(node.right);
                    }
                    if (i==size-1){
                        res.add(node.val);
                    }
                }
            }
            return res;
        }
    }

复杂度