Right Side View

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.

  • Time: O(N)
  • Space: O(1)
public List<Integer> rightSideView(TreeNode root) {
    List<Integer> result = new ArrayList<Integer>();
    rightView(root, result, 0);
    return result;
}

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

results matching ""

    No results matching ""