Practice › Trees
Height of a Binary Tree
Easy · Trees · Asked at Amazon, Microsoft, TCS, Infosys, Wipro
Print the height of the binary tree — the number of nodes on the longest root-to-leaf path.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
The height.
Constraints
- 1 ≤ number of nodes ≤ 10^4
Example:
3 9 20 -1 -1 15 7is root 3 with children 9 and 20; 20 has children 15 and 7.
Example 1
Input
7 3 9 20 -1 -1 15 7
Output
3
Example 2
Input
3 1 -1 2
Output
2
Hints
- The height of a node is 1 + the larger height of its two subtrees.
- An empty subtree has height 0 — that is the base case.
Approach
Recursive definition: height(null) = 0 and height(node) = 1 + max(height(left), height(right)). Every node is visited once. A BFS that counts levels gives the same answer without recursion, which is handy for very deep, skewed trees.
Complexity: O(n) time · O(h) recursion depth
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// Build a tree from level order where -1 means "no node".
Node *readTree() {
int k;
cin >> k;
vector<long long> v(k);
for (auto &x : v) cin >> x;
if (k == 0 || v[0] == -1) return nullptr;
Node *root = new Node(v[0]);
queue<Node *> q;
q.push(root);
int i = 1;
while (!q.empty() && i < k) {
Node *cur = q.front();
q.pop();
if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
i++;
}
return root;
}
int height(Node *node) {
if (!node) return 0;
return 1 + max(height(node->left), height(node->right));
}
int main() {
cout << height(readTree()) << "\n";
return 0;
}Python solution
import sys
from collections import deque
sys.setrecursionlimit(100000)
class Node:
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def read_tree():
"""Build a tree from level order where -1 means "no node"."""
data = list(map(int, sys.stdin.read().split()))
k, v = data[0], data[1 : data[0] + 1]
if not v or v[0] == -1:
return None
root = Node(v[0])
q, i = deque([root]), 1
while q and i < k:
cur = q.popleft()
if i < k and v[i] != -1:
cur.left = Node(v[i])
q.append(cur.left)
i += 1
if i < k and v[i] != -1:
cur.right = Node(v[i])
q.append(cur.right)
i += 1
return root
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
print(height(read_tree()))Java solution
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// Build a tree from level order where -1 means "no node".
static Node readTree(Scanner sc) {
int k = sc.nextInt();
long[] v = new long[k];
for (int i = 0; i < k; i++) v[i] = sc.nextLong();
if (k == 0 || v[0] == -1) return null;
Node root = new Node(v[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < k) {
Node cur = q.poll();
if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
i++;
}
return root;
}
static int height(Node node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String[] args) {
System.out.println(height(readTree(new Scanner(System.in))));
}
}Solve Height of a Binary Tree online · All practice problems