我需要找到二叉树的高度。我编写代码并获得比我应该得到的更多的代码。我不知道我的方法有什么问题?我做错了什么?这是我的代码:
public int getHeight(Height node) {
if (node == null) {
return 0;
} else {
int lDepth = getHeight(node.left);
int rDepth = getHeight(node.right);
if (lDepth > rDepth) {
return (lDepth) + 1;
} else {
return (rDepth) + 1;
}
}
}
public static void main(String[] args) {
treeHeight th = new treeHeight();
Scanner sc = new Scanner(System.in);
int i, t, n;
System.out.println("How many numbers you want to inout? ");
t = sc.nextInt();
for (i = 0; i < t; i++) {
System.out.println("Enter a number:");
n = sc.nextInt();
th.insert(th.root, n);
}
System.out.println("\n");
th.display(th.root);
System.out.println("\n");
System.out.println("Height of the tree is : " + th.getHeight(th.root));
}
答案 0 :(得分:0)
问题以这种方式定义树的高度:
二叉搜索树的高度是树根与其最远叶之间的边数。
您的方法计算节点而非边数,并且节点中的高度始终大于边缘中的高度,假设我们从“树”的定义中排除空图。只需从getHeight()
的顶级调用结果中减去一个(但不是从其递归调用的结果中减去)。