0199. Binary Tree Right Side View

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

Description

Given the root of 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.

Example 1:

**Input:** root = [1,2,3,null,5,null,4]
**Output:** [1,3,4]

Example 2:

**Input:** root = [1,null,3]
**Output:** [1,3]

Example 3:

**Input:** root = []
**Output:** []

Constraints:

  • The number of nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100

ac1: BFS

/**
 * 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> res = new ArrayList<Integer>();
        if (root == null) return res;
        Queue<TreeNode> q = new LinkedList<TreeNode>();

        q.offer(root);
        while (!q.isEmpty()) {
            int len = q.size();
            for (int i = 0; i < len; i++) {
                TreeNode curr = q.poll();
                if (curr.left != null) q.offer(curr.left);
                if (curr.right != null) q.offer(curr.right);
                if (i == len - 1) res.add(curr.val);
            }
        }

        return res;
    }
}

ac2: DFS

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        helper(root, res, 0);        
        return res;
    }

    private void helper(TreeNode root, List<Integer> res, int currDepth) {
        if (root == null) return;
        if (currDepth >= res.size()) res.add(root.val);
        helper(root.right, res, currDepth+1);
        helper(root.left, res, currDepth+1);
    }
}

Last updated