我正在自学考试,由于缺乏实例而遇到了问题。答案。练习声明如下:
"编写一个使用递归计算给定二叉树高度的算法,即。从根节点到叶节点的最长的现有路径。"
给出了方法的原始开始,并且必须修改此方法以形成最终答案。在此方法之外不允许使用其他方法:
// Binary tree height, find the longest path to a leaf node
public static int height(BTree t) {
return 0;
}
在每次调用函数之前,将一个节点添加到树中。 最终给定的树看起来像这样:
10
__/ \__
5 15
/ \ / \
3 8 12 18
\ /\
4 11 13
以下是我到目前为止所做的但是它无法正常工作:
// Binary tree height, find the longest path to a leaf node
public static int height(BTree t) {
BTreeNode n = t.getRoot();
int height = 0;
int calc = 0;
if (n == null)
{
return height;
}
else
{
while (n!=null) {
n = n.getLeftChild();
calc++;
}
}
if(calc > height) {
height = calc-1;
height = 0;
}
n = t.getRoot();
while (n!=null) {
n = n.getRightChild();
calc++;
}
if(calc > height) {
height = calc-1;
height = 0;
}
return height;
} // height()
请帮助我学习并通过考试,非常感谢所有帮助!
答案 0 :(得分:0)
awk
答案 1 :(得分:0)
在这种情况下,递归将是一个不错的选择。要获得高度,请从根节点开始,深度为0.您可以使用函数来获得最大深度。如果传递给它的节点为null(树的末尾),则此函数仅返回深度。否则它会调用自身,左右儿童的深度增加1(还有另一层,因此必须增加深度)。然后它返回找到的更高深度。代码看起来像这样:
public static int getMaxDepth(BTreeNode node, int depth) {
if (node == null) return depth;
return Math.max(getMaxDepth(node.getLeftChild(), depth + 1), getMaxDepth(node.getRightChild(), depth + 1));
}
这将遍历整棵树并找到最长的路径。 (我没有测试这段代码,但它应该可以工作。)
如果你想要一个简单的if子句来检查哪个深度更大,你可以避免Math.max()
,但我个人更喜欢这种方式。
您也可以尝试解析递归并将其替换为迭代。但是你必须编写更多的代码,这将更难以阅读和理解。没有递归的一种方法是跟踪当前层中的所有节点(及其深度)(例如,使用ArrayList),然后获取最后一层中节点的所有子节点。之后,使用找到的子项更新列表并增加深度。如果子项列表为空,则表示已到达树的末尾并返回深度。执行此操作的代码看起来像这样(再次未经测试):
public static int getMaxDepth(BTreeNode root) {
if (root == null) return 0;
List<BTreeNode> currentLayer = new ArrayList<>();
List<BTreeNode> children = new ArrayList<>();
int depth = 0;
currentLayer.add(root);
while (0 < currentLayer.size()) {
depth++;
children.clear();
for (BTreeNode node : currentLayer) {
BTreeNode left = node.getLeftChild();
if (left != null) children.add(left);
BTreeNode right = node.getRightChild();
if (right != null) children.add(right);
}
currentLayer.clear();
currentLayer.addAll(children);
}
return depth;
}