Java 二叉搜索树生成器
我试图构建一个二进制搜索树生成器方法。然而,我认为我遗漏了一些东西。我用Java 二叉搜索树生成器,java,tree,binary-search-tree,Java,Tree,Binary Search Tree,我试图构建一个二进制搜索树生成器方法。然而,我认为我遗漏了一些东西。我用inOrderPrint方法和treeHeigh方法测试了我的方法。我的方法的工作原理是根节点是第一个参数。第二个参数是另一个TreeNode节点。此参数是一个TreeNode,该方法应将自身重新排列为二叉搜索树 我的inOrderPrint给了我正确的打印,这使我假设我的buildBST正在工作。但是,我的treeHeight方法没有提供正确的输出。我非常确定我的inOrderPrint和treeHeight方法是正确创建
inOrderPrint
方法和treeHeigh
方法测试了我的方法。我的方法的工作原理是根节点是第一个参数。第二个参数是另一个TreeNode节点
。此参数是一个TreeNode
,该方法应将自身重新排列为二叉搜索树
我的inOrderPrint给了我正确的打印,这使我假设我的buildBST
正在工作。但是,我的treeHeight
方法没有提供正确的输出。我非常确定我的inOrderPrint
和treeHeight
方法是正确创建的
我相信我的buildBST
方法中缺少了一些逻辑,但我似乎无法说出它是什么
我的根集是14。
如果我将TreeNodes
与值5,10,3,20,50,25,40,1,2,18,100101
放在一起,我会得到这些数字的排序输出,但如果使用treeHeight
,我会在预期为7时得到5的输出
有人能告诉我哪里出了问题吗
二叉搜索树生成器
代码:
树高:
public static int treeHeight(TreeNode node) {
if (node == null) {
return 0;
} else {
int Ldepth = treeHeight(node.left);
int Rdepth = treeHeight(node.right);
return Math.max(Ldepth, Rdepth) + 1;
}
}
高度是5。树的高度肯定是5。使用这个小工具很容易看到
我不认为这是错的。。。用笔和纸做的我得到了最大高度5@gtgaxiola根为14,输入节点为5,10,3,20,50,25,40,1,2,18100101,我认为树的高度应该大于5。感谢您的努力请在可视化工具中测试您的输入。。。你会看到树的高度是5。13个值的深度可以在4到13之间。这就是为什么人们对最优二叉搜索树感兴趣。一个幼稚的实现运行O(n^{3})以及为什么Knuth在O(n^{2})中的算法是一个大问题。
public static void inOrderPrint(TreeNode node) {
if (node == null) {
return;
} else {
inOrderPrint(node.left);
System.out.println(node.data);
inOrderPrint(node.right);
}
}
public static int treeHeight(TreeNode node) {
if (node == null) {
return 0;
} else {
int Ldepth = treeHeight(node.left);
int Rdepth = treeHeight(node.right);
return Math.max(Ldepth, Rdepth) + 1;
}
}
14
/ \
5 20
/ /\
3 18 50
/ / \
1 25 100
\ \ \
2 40 101