【发布时间】:2021-11-29 18:21:39
【问题描述】:
我正在尝试使用迭代方法来计算我的二叉搜索树的高度,但我无法确定何时将 1 添加到我的高度变量,也就是当有新级别的节点时。这是我的插入方法:
public Node insertRec(Node x, String key) {
if (x == null)
{
x = new Node(key); // if bst is empty, add new node and return
height++;
return x;
}
if (key.compareTo(x.key) < 0) {
x.left = insertRec(x.left, key); // recursive calls to find correct spot to insert in the tree
}
else if (key.compareTo(x.key) > 0) {
x.right = insertRec(x.right, key);
}
return x; // returns unchanged node
}
如您所见,现在我只是在添加新节点时将高度加 1,然后我使用另一种方法仅返回该变量,但这不是高度的正确数字。我相信我需要某种测试,以便如果有新级别的节点,则将 1 添加到高度,但我不确定从哪里开始。
【问题讨论】:
-
不要增加高度,计算高度根据子节点的高度。
标签: java binary-search-tree nodes increment