Problem
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 depth of the two subtrees of everynode never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
1 | 3 |
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 | 1 |
Return false.
Solution
解析
根据平衡二叉树定义,每个节点子树之间的高度差不能超过1.所以我们先定义一个求二叉树高度的函数getDepth(),然后递归对二叉树节点进行判断。
Solution 1
1 | /** |
这种方法速度比较慢。原因在于,节点高度的重复计算。自上而下,节点的高度多次重复计算,提高了时间复杂度。
如果简化的话,想办法自下而上,减少重复计算。这里,修改getDepth()函数,让函数在求二叉树深度的同时,判断左右节点的高度差,如果大于1,返回-1(说明这棵二叉树一定不是平衡二叉树,及时停止)。
Solution 2
1 | /** |