针对于树的操作,大部分都是用递归操作的,根据递归运算,要确定重复循环的过程以及截止条件,不过针对二叉树,还是比较难思考的。
class Solution:
res=True
def IsBalance_Solution(self,pRoot):
self.judge(pRoot)
return self.res
def judge(self,root):
if not root:
return 0
left=1+self.judge(self.left)
right=1+self.judge(self.right)
if abs(left-right)>1:
self.rse=Flase
return max(left,right)
两步递归方法:
class Solution:
def IsBalance_Solution(self,root):
if not root:
return True
if abs(self.maxDepth(root.left)-self.maxDepth(root.right))>1:
return Flase
return self.IsBalance_Solution(self.left) and self.IsBalance_Solution(self.right)
def maxDepth(self,root)
if not root: return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1