199. Binary Tree Right Side View

Description

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

199. Binary Tree Right Side View_第1张图片
tree

You should return [1, 3, 4].

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Solution

Right-to-Left BFS, time O(n), space O(h)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List rightSideView(TreeNode root) {
        List list = new LinkedList<>();
        if (root == null) {
            return list;
        }
        
        Queue queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            list.add(queue.peek().val);
            
            while (size-- > 0) {
                TreeNode curr = queue.poll();
                if (curr.right != null) queue.offer(curr.right);
                if (curr.left != null) queue.offer(curr.left);
            }
        }
        
        return list;
    }
}

DFS, time O(n)

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.

用currDepth = result.size()作为条件还是挺妙的啊。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List rightSideView(TreeNode root) {
        List list = new LinkedList<>();
        rightSideViewRecur(root, 0, list);
        return list;
    }
    
    public void rightSideViewRecur(TreeNode root, int level, List list) {
        if (root == null) {
            return;
        }
        
        if (level == list.size()) {
            list.add(root.val);
        }
        
        rightSideViewRecur(root.right, level + 1, list);
        rightSideViewRecur(root.left, level + 1, list);
    }
}

你可能感兴趣的:(199. Binary Tree Right Side View)