oneby7

Binary Trees Breadth first: level by level

378. Bottom View of a Binary Tree

Medium

You are given root, the root node of a binary tree. Every node has a column and a row. The root is in column 0, a left child is one column to the left of its parent, and a right child is one column to the right. The row is the node's depth: the root is in row 0, its children in row 1, and so on.

Picture yourself looking up at the tree from below. In each column you see only the lowest node, the one with the largest row, and it hides the nodes above it. Return the values of the nodes you see, one per column, from the leftmost column to the rightmost.

Sometimes two nodes in a column are both the lowest. Then you see the one that comes last when their row is read from left to right, as the examples write it. Example 1 has such a tie.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

423687951

Input: root = [7, 2, 9, 4, 6, null, 1, null, null, 3, 8, 5]

Output: [4,3,6,5,1]

Explanation: The columns run from −2 to 2. 8 and 5 are both in row 3 and column 1, and nothing in column 1 is lower. Row 3 reads 3, 8, then 5 from left to right, so you see 5. In columns 0 and 2 you see 6 and 1, though neither is a leaf.

Example 2

-5-3−10⁹10⁹

Input: root = [-5, null, -1000000000, -3, 1000000000]

Output: [-3,-1000000000,1000000000]

Explanation: −3 is the left child of −1000000000, so it is in row 2 and column 0, below the root, and it hides the root.

Example 3

-469

Input: root = [6, -4, 9]

Output: [-4,6,9]

Explanation: Nothing lies below the root in column 0, so you see the root.

Check your understanding

Work out the answer for this input before you write any code.

root = [10, 20, 30, 40, 50, 60, 70]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.