按照剑指offer复现python版本的平衡二叉树的题时,发现无法通过,代码如下:
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
d = 0
return self.isBalanced(pRoot,d)
def isBalanced(self,pRoot, d):
if pRoot == None:
d = 0
return True
left = 0
right = 0
if self.isBalanced(pRoot.left, left) and self.isBalanced(pRoot.right, right):
diff = left - right
if abs(diff) <= 1:
d = 1 + max(left, right)
return True
return False
原因是python在传递参数时采用值传递,d,left,right经过self.isBalanced之后并没有改变数值,需要将值传递改成引用传递,改进后代码如下,即可通过
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
d = [0]
return self.isBalanced(pRoot,d)
def isBalanced(self,pRoot, d):
if pRoot == None:
d[0] = 0
return True
left = [0]
right = [0]
if self.isBalanced(pRoot.left, left) and self.isBalanced(pRoot.right, right):
diff = left[0] - right[0]
if abs(diff) <= 1:
d[0] = 1 + max(left[0], right[0])
return True
return False
另外一种方法是取返回值作为深度,即不需要考虑值传递和引用传递了,代码如下:
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
self.flag = True
self.isBalanced(pRoot)
return self.flag
def isBalanced(self,pRoot):
if pRoot == None:
#or self.flag == False:
d = 0
return d
left = self.isBalanced(pRoot.left)
right = self.isBalanced(pRoot.right)
if abs(left - right) > 1:
self.flag = False
return 0
d = 1 + max(left, right)
return d
参考链接:https://blog.csdn.net/u010005281/article/details/79718391