简体   繁体   中英

Binary Search Tree Construction of height h

Given the first n natural numbers as the keys for a BST , How can I determine the root node of all possible tree that have a height 'h' .

I already came up with a brute force method where I constructed all possible trees with n nodes and then selected the trees which have a height h but it has a time complexity of nearly O(n!) . Can someone please suggest a better method which would me more efficient ?

Problem statement. Given natural numbers n and h , determine exactly all elements root in 1..n such that root is the root of a binary search tree on 1..n of height h .

Solution . We can construct a degenerate binary search tree on 1..n starting from any number in 1..n by splitting it up at root . This changes the lower bounds from the old solution to h-1 , while the upper bounds remain the same, rendering the full bounds as follows:

 h-1 <= max(root-1, n-root) <= 2^h - 1

Old solution (correct only for full binary trees). A full binary tree with height h has at least 2h+1 nodes, and at most 2^(h+1)-1 nodes . It's easy to see that these bounds are tight, not only for binary trees, but also for binary search trees. In particular, they apply to the left and right subtrees of your root . Since this is a binary search tree on 1..n , you will have that left contains exactly the elements 1..(root-1) , and right contains exactly the elements (root+1)..n .

This means that the following is both a necessary and sufficient condition: The larger of the subtrees left and right must satisfy the inequalities

2*(h-1) + 1 <= nodes(subtree) <= 2^h - 1

In other words, the possible values of root are exactly all values in 1..n satisfying

2*(h-1) + 1 <= max(root-1, n-root) <= 2^h - 1

Update. I blindly looked at an inequality I found at wikipedia without realizing that it only applied to full binary trees.

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