【Leetcode_總結】110. 平衡二叉樹 - python
阿新 • • 發佈:2019-01-11
Q:
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過1。
示例 1:
給定二叉樹 [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回 true
。
示例 2:
給定二叉樹 [1,2,2,3,3,null,null,4,4]
1 / \ 2 2 / \ 3 3 / \ 4 4
連結:https://leetcode-cn.com/problems/balanced-binary-tree/description/
思路:此題利用了 二叉樹的最大深度 的部分程式碼,逐一遍歷節點,判斷子樹是否是平衡二叉樹
程式碼:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if root.right and root.left: if abs(self.maxDepth(root.right) - self.maxDepth(root.left)) <= 1 : return self.isBalanced(root.right) and self.isBalanced(root.left) else: return False if not root.left: if abs(self.maxDepth(root.right)) <= 1: return self.isBalanced(root.right) else: return False if not root.right: if abs(self.maxDepth(root.left)) <= 1: return self.isBalanced(root.left) else: return False def maxDepth(self, root): if not root: return 0 else: return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)