简体   繁体   中英

Insert element to binary tree at specific position

It might be an newbie question but I am struggling to get an answer to this question. Consider an binary tree(not binary search tree) like this:

              root
      child1        child2

  child3 child4

I need to add "child5" at the left child of "child2". How an I do that? I know the way to add nodes for binary search tree. Snapshot of the same is something like this:

if (newNode->val < root->data) {
  -> pick left node
} else {
  -> pick right node
}

Since tree is not an BST, this solution would not be correct.

An pictorial representation of what I am trying to say:

               1
      2                3

  4      5

In above tree, '6' should be added as left of '3'.

Okay. I think answer to this would be something like this:

Little tweak in BFS would be required. When you pop up the items from the queue, check if any of the children is empty. The first empty child slot is the place you want to add to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM