Skip to content

623. Add One Row to Tree #164

Discussion options

You must be logged in to vote

We can use either Breadth-First Search (BFS) or Depth-First Search (DFS) to traverse the tree. The idea is to add the new row at the specified depth.

Approach:

  1. Edge Case: If the depth is 1, we need to add the new node as the new root of the tree.
  2. DFS or BFS: Traverse the tree to reach nodes at depth - 1, then:
    • Insert new nodes with value val as left and right children of each node.
    • The original left child of the node becomes the left child of the newly inserted left node.
    • Similarly, the original right child becomes the right child of the newly inserted right node.

Steps:

  1. If depth == 1, create a new root and attach the original tree as the left child of the new root.
  2. Otherwise, trave…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Sep 8, 2024
Maintainer Author

@basharul-siddike
Comment options

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants