1. 程式人生 > >39平衡二叉樹判斷python

39平衡二叉樹判斷python

題目:輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。若左右子樹深度差不超過1則為一顆平衡二叉樹。
思路:1、使用獲取二叉樹深度的方法來獲取左右子樹的深度
2、左右深度相減,若大於1返回False
3、通過遞迴對每個節點進行判斷,若全部均未返回False,則返回True

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution
:
def getDeepth(self, Root): if Root is None: return 0 nright = self.getDeepth(Root.right) nleft = self.getDeepth(Root.left) return max(nright, nleft)+1 def IsBalanced_Solution(self, pRoot): # write code here if pRoot is None: return
True right = self.getDeepth(pRoot.right) left = self.getDeepth(pRoot.left) if abs(right - left) >1: return False return self.IsBalanced_Solution(pRoot.right) and self.IsBalanced_Solution(pRoot.left)

進階思路:
採用後續遍歷,當遍歷到根節點時,每個節點只會遍歷一次
以下程式無法執行,僅提供思路

class
Solution:
def IsBalanced(self, pRoot, depth): if pRoot is None: return True if self.IsBalanced(pRoot.right, right) and self.IsBalanced(pRoot.left, left): diff = abs(left - right) if diff <= 1: depth = max(left, right) +1 return True return False def IsBalanced_Solution(self, pRoot): # write code here depth = 0 return self.IsBalanced(pRoot, depth)