199. Binary Tree Right Side View(二叉树的右视图)

题目描述

199. Binary Tree Right Side View(二叉树的右视图)

题目链接

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

方法思路

Apprach1:
基于层序遍历,只添加每层的最后一个节点的值。

class Solution {
    //Runtime: 1 ms, faster than 72.32%
    //Memory Usage: 37.1 MB, less than 86.24%
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new LinkedList<>();
        if(root == null) return ans;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new LinkedList<>();
            while(size-- > 0){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
            ans.add(list.get(list.size() - 1));
        }
        return ans;
    }
}

Apprach2:
The core idea of this algorithm:
1.Each depth of the tree only select one node.
2. View depth is current size of result list.

public class Solution {
    //Runtime: 1 ms, faster than 72.32%
    //Memory Usage: 37.3 MB, less than 27.53%
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        rightView(root, result, 0);
        return result;
    }
    
    public void rightView(TreeNode curr, List<Integer> result, int currDepth){
        if(curr == null){
            return;
        }
        if(currDepth == result.size()){
            result.add(curr.val);
        }
        
        rightView(curr.right, result, currDepth + 1);
        rightView(curr.left, result, currDepth + 1);
        
    }
}