劍指Offer38:平衡二叉樹
阿新 • • 發佈:2018-12-26
思路:
判斷是否是平衡二叉樹,即判斷任何一個節點的左子樹和右子樹的高度差的絕對值小於等於1。最直接的做法,遍歷每個結點,藉助一個獲取樹深度的遞迴函式,根據該結點的左右子樹高度差判斷是否平衡,然後遞迴地對左右子樹進行判斷。
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here if pRoot == None: return True if abs(self.TreeDepth(pRoot.left)-self.TreeDepth(pRoot.right)) > 1: return False return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) def TreeDepth(self, pRoot): # write code here if pRoot == None: return 0 nLeft = self.TreeDepth(pRoot.left) nRight = self.TreeDepth(pRoot.right) return max(nLeft+1,nRight+1)