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);
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);
counter = 0;
}
return counterOld;
}
}
import java.util.Scanner;
public class BinaryTester {
public static void main(String[] args) {
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
I have mixed results with a counter of tree height functions. I would like to calculate how low a tree falls based on the lowest node. For example, the tree at the top should be 3 in height, with the root being counted at 0. I get an incorrect result of height 1. I get the correct results if I enter this tree:
400
/ \
300 10
/ / \
100 4 5
/
3
This tree will give me a height of 3, which I was looking for. Does anyone know how I can configure my code to account for all trees?
source
share