java调试自定义二叉树特定的总(最大)深度方法
至于我的问题:我有一个节点类:
public class Node<E> {
private E value;
private Node<E> left;
private Node<E> right;
public Node(E value) {
this.value = value;
this.left = null;
this.right = null;
}
这个类有两个计算节点深度的方法(二叉树)。方法totaldepth()
是我自己写的,它给出了一个错误的答案,我需要你的帮助。方法maxDepth(Node node)
给出了正确的答案,并被我用作参考材料。你能帮我调试一下totalDepth
方法吗?对我来说,结果看起来和maxDepth
一样
错误代码:
public int totalDepth() {
// initialize variabele depth
int depth = 0;
// reached leaf return 0
if (right == null && left == null) {
return 0;
}
// not yet reached leaf, continue deeper
else {
int leftdepth = 0;
int rightdepth = 0;
// left node is not null continue going left
if (left != null) {
leftdepth = left.totalDepth();
}
// right node is not null continue going right
if (right != null) {
rightdepth = right.totalDepth();
}
if (leftdepth > rightdepth) {
// 1 is needed because each call to totalDepth raises depth by 1
depth = leftdepth + 1;
}
else {
depth = rightdepth + 1;
}
}
return depth;
}
正确代码:
public int maxDepth(Node node) {
if (node == null) {
return (0);
}
else {
// compute the depth of each subtree
int leftDepth = maxDepth(node.left);
int rightDepth = maxDepth(node.right);
// use the larger one
if (leftDepth > rightDepth)
return (leftDepth + 1);
else
return (rightDepth + 1);
}
}
另外,我刚刚开始学习如何编码,所以请原谅我所做的所有低效的事情。提前谢谢你帮助我
# 1 楼答案
你的
totalDepth
方法将不起作用,因为你有一棵树,你实际上不知道从左到右有多少个元素。不管这棵树是否平衡。所以,唯一的方法是使用Breadth-first search
或Depth-first search
算法,它们基于递归函数,比如maxDepth(Node node)
方法