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 every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
思路:
1、从题目本意高度之差入手、对于每一个节点来说、子树高度差<=1才可以
2、这里有一个trick,如果返回的是-1、则为false、如果不是-1、则为true
如果节点为null、则return 0
不然则计算左子树的高度记为leftHeight、如果leftHeight为-1、则return -1
不然计算右子树的高度记为rightHeight、如果rightHeight为-1、则return-1
不然计算左右子树的高度之差、如果大于1、则return-1
不然return leftHeight和rightHeight中的较大者+1