Java tree height recursion

ww‮uttual.w‬ri.com
Java tree height recursion

To find the height of a tree using recursion in Java, you can define a recursive function that takes in a TreeNode as its argument and returns an integer representing the height of the tree rooted at that node.

Here is an example of how you could define such a function:

public static int getHeight(TreeNode root) {
    if (root == null) {
        return 0;
    }
    return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}

This function works by first checking if the current node is null, in which case it returns 0. If the node is not null, it returns 1 plus the maximum of the heights of the left and right subtrees.

To find the height of the entire tree, you can call this function with the root node of the tree as the argument.

Created Time:2017-10-17 20:18:54  Author:lautturi