Skip to content
Advertisement

Covert Binary Tree to Doubly Linked List (Microsoft Interview)

We are converting a binary tree into a DLL, in place also we are using in order traversalto do so.

Read more hereLink

My Code:

JavaScript

My problem: The head is always None and hence I cannot print the converted list. What is wrong with this code or my logic?

Advertisement

Answer

Your code has many Pitfalls, the main reason why it return none is because from btToDll returns nothing, also it doesn’t change the value of head, which it still None.

Instead of trying to repair your code, I preferred to go in a different Approach all in once.

Basically, I found a trick to get the result:

  1. Go down to the most left Node which becomes the HEAD.
  2. Check if from the Head You can go Up one, then left- left. or Up One right right and so on. If you can go Left then set the current node as the left bottom node. Do this untill there isn’t any Node. Add the Previous node in the DLL list
  3. Caluclate the current node, its previous and the Right node from the Previoys.
  4. Go back from the Binary Tree, one reach the Root node (10), repeat the same pattern.

You will see that basically, if in any given Sub-node, there is a left node, then you calculate the entire Triangle, the most important node is always the left and becomes the current node. If left node is not present, then the Parent node becomes the current node, then you need to check whether the parent has a right node not.

I prepared some pictures, is much better to visualize this than explain it.

Take this Binary Tree:

enter image description here

First Step | Go To the most far left node as possible

enter image description here

Second Step | Calculate the First Triange

Note: If the Right bottom Node (30) HAS a left child node, then 30 won’t be added, which is the case of this example, instead it goes to the next step.

enter image description here

Step 3 | Go to the next Triangle step of the Child’s child node##

enter image description here

Step 4 | Now go up to the root node and calculate the left side of BT

Note: See the complete path of this algorithm, again I imagine that as many small triangles that are calculated Separately.

enter image description here

Source Code

NOTE: Is been lengthy, but I did it on the fly, can be improved.

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement