import java.util.Scanner;
public class BinaryTree {
private int info;
private BinaryTree left;
private BinaryTree right;
private int height = 1;
public BinaryTree()
{
left = null;
right = null;
}
public BinaryTree(int theInfo)
{
Scanner sc = new Scanner(System.in);
int intNum;
String s;
info = theInfo;
System.out.print("Does the node " + info + " have a left child (y or n)? ");
s = sc.next();
if (s.equals("y"))
{
System.out.print ("What value should go in the left child node? ");
intNum = sc.nextInt();
left = new BinaryTree(intNum);
}
System.out.print("Does the node " + info + " have a right child (y or n)? ");
s = sc.next();
if (s.equals("y"))
{
System.out.print ("What value should go in the right child node? ");
intNum = sc.nextInt();
right = new BinaryTree(intNum);
}
}
int heightLeft = 0;
int heightRight = 0;
public int getHeight()
{
int counterOld = 0;
int counter = 0;
if (left != null)
{
counter++;
if (counter > counterOld)
{
counterOld = counter;
}
counter += left.getHeight();
}
if (left == null)
{ System.out.println("counter is: " + counter + " and counterOld is: " + counterOld);
/*if (counter > counterOld)
{
counterOld = counter;
} */
counter = 0;
}
if (right != null)
{
counter++;
if (counter > counterOld)
{
counterOld = counter;
}
counter += right.getHeight();
}
if (right == null)
{ System.out.println("counter is" + counter + " and counterOld is: " + counterOld);
/*if (counter > counterOld)
{
counterOld = counter;
} */
counter = 0;
}
return counterOld;
}
}
import java.util.Scanner;
public class BinaryTester {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTree myTree;
Scanner sc = new Scanner(System.in);
int intNum;
System.out.print("What value should go in the root? ");
intNum = sc.nextInt();
myTree = new BinaryTree(intNum);
System.out.println("Height is " + myTree.getHeight());
}
}
400
/
300
/
200
/
100
我的树高函数计数器混合了结果。我想根据最低节点计算树的下降程度。例如,上面的树应该是3的高度,根被计为0.我得到高度不正确的结果1.如果我输入这样的树,我得到正确的结果:
400
/ \
300 10
/ / \
100 4 5
/
3
这棵树给我的高度为3,这正是我所寻找的。任何人都知道我如何调整我的代码来解释所有树木?
答案 0 :(得分:4)
public int getHeight(BinaryTree node){
if(node == null){
return 0;
}
int left = getHeight(node.left);
int right = getHeight(node.right);
return Math.max(left, right) + 1;
}
此方法提供一个基于高度的高度。如果你想在零开始计数,那么你可以从中减去一个,例如
getHeight(tree) - 1
答案 1 :(得分:3)
虽然有一个公认的答案,但我想提供一个略有不同的选择。
我认为这样的方法更适合作为实例方法(我们不应该尝试使用OOP范例,因为我们使用Java?; P)
代码如下:
class BinaryTree {
private BinaryTree left, right;
int getHeight() {
if (left == null && right == null) {
return 0;
} else {
int leftHeight = (left==null? 0: left.getHeight());
int rightHeight = (right==null? 0: right.getHeight());
return Math.max(leftHeight ,rightHeight) + 1;
}
// whole method can even shrink to one-line like
// return Math.max((left==null? -1: left.getHeight()),
// (right==null? -1: right.getHeight()))
// + 1;
}
}
使用它时,imho更直观:
BinaryTree tree = ....;
int height = tree.getHeight();
(它给你基于0的树高; P)