Here is the javascript implementation:

It actually goes through each level. When it reaches the first leaf node, it returns the depth.

The code can be changed a little to return the minimum path, like 'root'-2-5.

Another question can use similar algorithm: add a node into one height balanced tree, make sure it is still a height-balanced tree.

A binary tree is height balanced if the difference between any two leaves is at most 1.

The algorithm here is to traversal each level. When the first undefined leaf found, that is the position to add the new node.

Another balanced tree is weight balanced tree. A tree is weight balanced if the diff between total nodes of the left subtree and the right subtree is at most 1.

If one more node need to be added, for height balanced tree, you can add it to right of b, or left/right of d.

But for weight balanced tree, you can only add it to left/right of d.

## No comments:

## Post a Comment