后序遍历 + 剪枝 (从底至顶)
此方法为本题的最优解法,但剪枝的方法不易第一时间想到。
思路是对二叉树做后序遍历,从底至顶返回子树深度,若判定某子树不是平衡树则 “剪枝” ,直接向上返回。
复杂度分析:
时间复杂度 O(N)O(N): NN 为树的节点数;最差情况下,需要递归遍历树的所有节点。
空间复杂度 O(N)O(N): 最差情况下(树退化为链表时),系统递归需要使用 O(N)O(N) 的栈空间。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def inner_func(root):
if not root:
return 0
l = inner_func(root.left)
if l is False:
return False
r = inner_func(root.right)
if r is False:
return False
return max(l, r) + 1 if abs(l - r) <= 1 else False
return True if not root or inner_func(root) else False
[题目源于leetcode]