LeetCode 199: Binary Tree Right Side View

/**
 * 199. Binary Tree Right Side View
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root,0,res);
        return res;
    }
    
    public void helper(TreeNode root, int level, List<Integer> res){
        if(root == null) return;
        if(level == res.size())
            res.add(root.val);
        helper(root.right,level+1,res);
        helper(root.left,level+1,res);
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root==null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int cnt = queue.size();
            for(int i=0;i<cnt;i++){
                TreeNode tmp = queue.poll();
                if(i==cnt-1)
                    res.add(tmp.val);
                if(tmp.left!=null)
                    queue.add(tmp.left);
                if(tmp.right!=null)
                    queue.add(tmp.right);
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/AAAmsl/p/12793769.html