#K51407. Balanced Binary Tree Checker
Balanced Binary Tree Checker
Balanced Binary Tree Checker
You are given a binary tree in the form of a level order traversal. Each node in the tree is represented by an integer, and missing nodes are denoted by the string null
. A binary tree is said to be balanced if, for every node in the tree, the difference between the heights of its left and right subtrees is at most 1. For an empty tree, consider it as balanced.
Your task is to determine whether the given binary tree is balanced.
The tree is provided as a single line of input, where the node values are separated by spaces. For example, the input:
5 2 8 1 3 null 9
represents the following tree:
5 / \ 2 8 / \ 1 3 9
The expected output for the example above is True
because the tree is balanced.
Note: The output should be printed to stdout.
inputFormat
The input consists of a single line containing space-separated tokens representing the level order traversal of the binary tree. Each token is either an integer (node value) or the string null
, which represents a missing node.
Examples:
5 2 8 1 3 null 9
1 null 3 2
1
null
(represents an empty tree)
outputFormat
Output a single line containing either True
or False
(without quotes). True
means the tree is balanced, while False
means it is not.
5 2 8 1 3 null 9
True