#C13100. Check if a Binary Tree is Height-Balanced
Check if a Binary Tree is Height-Balanced
Check if a Binary Tree is Height-Balanced
A binary tree is considered height-balanced if for every node in the tree, the difference in the heights (depths) of the left and right subtrees is at most 1. In this problem, you are given the level-order traversal of a binary tree where missing nodes are represented by the token null
. Your task is to determine whether the tree is height-balanced.
The height of a node is defined as the number of edges in the longest path from that node to a leaf. A tree with no nodes is considered balanced.
Note: The input is given via standard input (stdin) and the output should be printed to standard output (stdout) as either True
or False
.
inputFormat
The input consists of a single line containing space-separated tokens that represent the nodes of the binary tree in level-order. Each token is either an integer (the value of the node) or the string null
(representing a missing node). For example:
3 9 20 null null 15 7
represents the binary tree:
3 / \ 9 20 / \ 15 7
outputFormat
Output a single line: True
if the binary tree is height-balanced, or False
otherwise.
3 9 20 null null 15 7
True