简体   繁体   English

高度为h的二叉搜索树的构造

[英]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' . 给定前n个自然数作为BST的键,如何确定高度为'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!) . 我已经想出了一种蛮力方法,其中我用n个节点构造了所有可能的树,然后选择了高度为h但时间复杂度接近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 . 鉴于自然数nh ,确定到底的所有元素root1..n使得root是在二叉搜索树的根1..n高度的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 . 我们可以从1..n任何数字开始在1..n上构建简并的二叉搜索树,方法是将其在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 ,而上限保持不变,从而呈现出完整的边界,如下所示:

 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 . 高度为h完整二叉树至少具有2h+1节点,并且最多具有2^(h+1)-1节点 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 . 特别是,它们适用于leftright您的子树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 . 由于这是1..n上的二叉搜索树,因此您将使left的元素正好包含元素1..(root-1) ,而right的元素right包含元素(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 这意味着以下条件既是必要条件,也是充分条件: leftright较大子树必须满足不等式

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 换句话说, root的可能值恰好是1..n满足的所有值

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. 我盲目地看了我在Wikipedia上发现的不平等,却没有意识到它仅适用于完整的二叉树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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