Last updated
Was this helpful?
Last updated
Was this helpful?
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.
看到二叉树先想分治。这道题和上道题的区别在于不只是记录深度,还要进行比较。 直接的想法是用两次分治,外层判断isBalanced, isBalanced内部再用分治算depth。 但这么做会重复计算树的深度,时间复杂度O(n^2). 此时我们可以对depth()进行特殊处理,让它在算深度时判断是否balanced, 如果不balance直接返回-1。 因为我们的目标不是计算深度,而是只要有imbalanced就返回即可。
一次分治遍历: O(n)
用stack帮助遍历, 用map记录每个遇到过的节点它的子树最大深度.