FastPrepLeft View of a Binary Tree

Left View of a Binary Tree

Mygate logoMygate● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Given the root of a binary tree, return its left view as a list of node values from top to bottom.

At each depth, include the leftmost existing node when the nodes at that depth are ordered from left to right. Include one value for every nonempty depth, even when values repeat.

An empty tree returns an empty list. The tree is displayed in level order, using null for missing children.

Function

leftView(root: TreeNode) → List<Integer>

Examples

Example 1

root = [1,2,3,null,4,5,6]return = [1,2,4]

The first nodes at depths 0, 1, and 2 have values 1, 2, and 4.

Example 2

root = [8,null,9,null,10]return = [8,9,10]

There is one existing node at each depth. All three are visible despite having only right-child links.

Constraints

  • The tree has 0 to 5000 nodes.
  • Each node value is an integer in [-10^6, 10^6].
  • Each node has at most two children, and the input is a valid tree with no cycles or shared child nodes.

More Mygate problems

See Mygate hiring insights
public List<Integer> leftView(TreeNode root) {
    // Return the leftmost node value at every depth.
}
root[1,2,3,null,4,5,6]
expected[1,2,4]
Checking account…