Binary Search Tree of Strings (before balancing)

一世执手 提交于 2020-01-05 12:11:47

问题


I'm reading up on Binary Search Trees and I have a question to answer similar to Ordered Binary Tree of Strings

Are the trees I've drawn below correct for before and after balancing? The data being entered are the strings, in order of, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus

Before balancing:

      Mercury
     /       \
   Earth     Venus
     \        /
    Mars   Saturn
    /         \
Jupiter      Uranus

After balancing:

          Mercury
         /       \
   Jupiter        Uranus
   /     \        /     \
Earth   Mars   Saturn  Venus

Is it also correct that the depth of the first tree is 3 and the depth of the second tree is 2, and that the maximum size is 7 (based on n = 2^(d+1)-1 where d = depth?


回答1:


Yes, the balancing looks correct as the binary search tree ordering is correct (for any given node, all nodes in the left subtree are smaller and all nodes in the right subtree are larger) and it's perfectly balanced.

Although I'm not sure there's a generic "balance the tree" algorithm (at least not one I've heard of). There are however self-balancing BST's like red-black trees and AVL trees.

Yes, the depths are correct, as per Wikipedia:

The depth (or height) of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a depth of zero.

Yes, the maximum size calculation is also correct. You can think of this as follows:
The maximum size is 1 + 2 + 4 + 8 + ... + 2depth (each term corresponds to the maximum number of nodes per level).
That is 1111111...111 (depth 1's) in binary.
And, of course, the above plus one is 100000...000 (depth 0's), which is 2depth + 1.
Subtracting the one again, we get 2(depth + 1) - 1.



来源:https://stackoverflow.com/questions/20554826/binary-search-tree-of-strings-before-balancing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!