-2
我想计算一个二叉树的直径,为此我创建了一个getDiameter()函数。现在在这个函数中,我需要调用Binary Tree的findHeight()函数,它返回二叉树的高度。在代码1和代码2中计算高度的2个函数在概念上略有不同。 在代码1我正在考虑单节点(只有根)的树的高度是1,在代码2中,我考虑单节点树的高度是0.所以在代码1的基本情况下,我返回0和code2我已经返回-1。我很困惑,其代码是正确的使用CODE1或代码2,因为直径的答案将会变化....递归使用树的高度的二叉树的直径?
public static int getDiameter(BinaryTreeNode root) {
if (root == null)
return 0;
int rootDiameter = findHeight(root.getLeft()) + findHeight(root.getRight()) + 1;
int leftDiameter = getDiameter(root.getLeft());
int rightDiameter = getDiameter(root.getRight());
return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
}
code1
public static int findHeight(BinaryTreeNode node) {
if(node == null)
return 0;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}
Code 2
public static int findHeight(BinaryTreeNode node) {
if(node == null)
return -1;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}