logo CodeStepByStep logo

height

Language/Type: Java binary trees
Related Links:

Write a method named height that returns the height of a tree. Your method accepts as its parameter a TreeNode that refers to the root of the tree. The height is defined to be the number of levels (i.e., the number of nodes along the longest path from the root to a leaf). The empty tree has height 0, a tree of one node has height 1, a root node with one or two leaves as children has height 2, and so on. For example, the following tree has a height of 4:

(7 (4 (2 (1) (3)) (5 / (6))) (8))

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode() { ... }
    public TreeNode(int data) { ... }
    public TreeNode(int data, TreeNode left, TreeNode right) { ... }
}
Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.