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,

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<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if (root == null) {
            return list;
        }
        
        Queue<TreeNode> 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<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        rightSideViewRecur(root, 0, list);
        return list;
    }
    
    public void rightSideViewRecur(TreeNode root, int level, List<Integer> 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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容