Height of a Binary Tree
Problem
The tree is given in level order on one line, with null for a missing child. Print its height: the number of nodes on the longest path from the root down to a leaf. An empty tree has the height 0.
Constraints
- 0 <= n <= 10^4 nodes
Examples
Input
3 9 20 null null 15 7
Output
3
Solutions
A tree is a root with two smaller trees. So the height is one more than the height of the taller child tree. An empty tree is the base case with height 0.
/*
* Problem : Process a binary tree.
* Input : One line: the tree in level order, null for a missing child.
* Output : The height.
* Approach: Recursion on both children.
* Time : O(n)
* Space : O(h)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: A tree node has a value and links to the left and right child. null means: no child.
static class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
// This method builds a tree from the level order tokens. A queue keeps the nodes that still need children.
static TreeNode build(String[] tokens) {
if (tokens.length == 0 || tokens[0].equals("null")) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(tokens[0]));
java.util.ArrayDeque<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < tokens.length) {
TreeNode node = queue.poll();
if (i < tokens.length && !tokens[i].equals("null")) {
node.left = new TreeNode(Integer.parseInt(tokens[i]));
queue.add(node.left);
}
i++;
if (i < tokens.length && !tokens[i].equals("null")) {
node.right = new TreeNode(Integer.parseInt(tokens[i]));
queue.add(node.right);
}
i++;
}
return root;
}
// This method returns the height of the tree. It asks both children and takes the larger answer plus 1.
static int height(TreeNode node) {
// Step 2: An empty tree has the height 0. This is the base case.
if (node == null) {
return 0;
}
// Step 3: The height is 1 (this node) plus the height of the taller child.
return 1 + Math.max(height(node.left), height(node.right));
}
// This method solves the task. It receives the input and returns the answer.
static int solve(String s) {
return height(build(s.trim().split(" ")));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- What is the height of an empty tree?