110. Balanced Binary Tree
Question:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of
Example:
Input: root = [3,9,20,null,null,15,7]
Output: true
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Input: root = []
Output: true
Source code
Version 1
Idea:
We can calculate the depth of subnodes and use it to compare. How to get calculate the depth for binary tree? You can refer to Maximum Depth of Binary Tree.
So, declare a getDepth() function to implement the depth of binary tree. At 18 line, abs(left_depth - right_depth) > 1
is based on a rule of height-balanced binary tree.
Time complexity: O(n)
// n: the total of nodes Space complexity: O(H) // H: the height of tree
1 | /** |