題目:


python3代碼:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
return self.isBalanced(root.left) and self.isBalanced(root.right) and abs(self.getHeight(root.left) - self.getHeight(root.right)) <=1
def getHeight(self, root: TreeNode) -> int:
if not root:
return 0
leftHeight = self.getHeight(root.left)
rightHeight = self.getHeight(root.right)
if leftHeight > rightHeight:
return leftHeight + 1
else:
return rightHeight + 1
思路:
根據題目的說法,兩邊的子樹高度不超過1,就是平衡樹,那么就可以根據整體高度來判斷
如果覺得不錯,就點贊或者關注或者留言~
謝謝~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/249902.html
標籤:python
