LeetCode 623. Add One Row to Tree — Explained Python3 Solution

 

Photo by trevor pye on Unsplash

Problem Description

Given the root of a binary tree, then the value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.

The adding rule is: given a positive integer depth d, for each NOT null tree nodes N of depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.

Example 1:

Input: 
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5
v = 1
d = 2
Output: 
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5

Example 2:

Input: 
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5
v = 1
d = 1
Output: 
         1
/
4
/ \
2 6
/ \ /
3 1 5

Solution

The key to this problem is that I need to:

1, know what’s the current depth for a node I visit now.

2, when current depth == d-1, I need to create 2 new children nodes and ask the left child’s left pointing to the current node’s left and the right child’s right pointing to the current node's right.

One corner case is what if d ==1. The problem description mentions that during an interview one may be expected to ask in the first place. So it may be a good practice to not look at the examples after reading the problem description; instead, think about the possible examples (to cover as many as possible scenarios) and then read further on provided examples to compare and reflect.

With the above explanation, hopefully below 2 solutions make more sense.

Recursive (DFS) Solution

Non-recursive(BFS) Solution

Time & Space Complexity

For both above solutions, assuming if there are N nodes, in general, the nodes I need to visit are directly related to N. Therefore the time complexity is also O(N).

When it comes to space complexity:

  1. The recursive solution requires O(1) space if the function calling stack is not calculated; otherwise, it’s O(N) since the more nodes you have, on average, the deeper you need to go.
  2. The non-recursive solution needs to store one layer of nodes so it is O(x) where x is the maximum possible nodes in a layer of the tree.

Extended Reading

Python3 cheatsheet
Algorithm Cheatsheet (continuously updated)

Comments

Popular posts from this blog

Leet Code 1060. Missing Element in Sorted Array — Explained Python3 Solution

Leet Code 84. Largest Rectangle in Histogram — Graphically Explained Python3 Solution

LeetCode 23. Merge k Sorted Lists— Graphically Explained Python3 Solution