Balanced Binary Tree Check
Problem
The tree is given in level order on one line, with null for a missing child. A tree is balanced when, for every node, the heights of its left and right subtrees differ by at most 1. Print true or false.
Constraints
- 1 <= n <= 10^4 nodes
Examples
Input
3 9 20 null null 15 7
Output
true
Input
1 2 null 3
Output
false
Solutions
One recursion returns the height, and uses -1 to say 'not balanced below'. As soon as a -1 appears it goes up unchanged, so every node is visited once.
/*
* Problem : Process a binary tree.
* Input : One line: the tree in level order, null for a missing child.
* Output : Balanced or not.
* Approach: Height with a -1 mark.
* 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;
}
// Step 2: Returns the height of the tree, or -1 if some node below is not balanced.
static int check(TreeNode node) {
if (node == null) {
return 0;
}
int left = check(node.left);
if (left < 0) {
return -1;
}
int right = check(node.right);
if (right < 0) {
return -1;
}
// Step 3: This node is balanced when the two heights differ by at most 1.
return Math.abs(left - right) <= 1 ? 1 + Math.max(left, right) : -1;
}
// This method solves the task. It receives the input and returns the answer.
static boolean solve(String s) {
return check(build(s.trim().split(" "))) >= 0;
}
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)
- How can a height tell about balance too?