Leetcode[623] Add One Row to Tree

Bryan W.
2 min readMar 10, 2021

Given the root of a binary tree, then 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 in 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.

Notes

  • The given d is in range [1, maximum depth of the given tree + 1].
  • The given binary tree has at least one tree node.

Difficulty

  • Level: Medium
  • Acceptance: 52.7%

Solution

Time Complexity: O(n), Space Complexity: O(n)

Analysis

I used recursion to traverse the nodeTree and add the row at the specified depth d. Assigning the root as d-1, I looped till depth of 1, where I will either add a new TreeNode with value v and join it with the next left or right node or just add a new TreeNode if the next node is null. If the starting depth of d is equal to 1, return a new TreeNode of value v with the current root as a left subtree.

--

--

Bryan W.

I have a passion for coding | Salesforce Developer