Binary Tree Right Side View

Problem

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,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].

Solution

Traversal with Depth Solution

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

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

Analysis

A typical tree traversal solution
We traversal the entire tree by the order root - right - left with depth passed
And we use res.size() == depth to update the res

results matching ""

    No results matching ""