请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
输入:{8,6,6,5,7,7,5}
输出:true
输入:{8,6,9,5,7,7,5}
输出:false
思路一: 二叉树就要想到用递归
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
return self.compare(pRoot.left,pRoot.right)
def compare(self,pRoot1,pRoot2):
if not pRoot1 and not pRoot2:
return True
if not pRoot1 or not pRoot2:
return False
if pRoot1.val == pRoot2.val:
if self.compare(pRoot1.left, pRoot2.right) and self.compare(pRoot1.right, pRoot2.left):
return True
return False
思路二: 递归的另一种思路
两种写法:调用函数写在外部
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
return self.Traversal(pRoot.left,pRoot.right)
def Traversal(self,pRoot1,pRoot2):
if not pRoot1 and not pRoot2:
return True
elif pRoot1 and pRoot2 and pRoot1.val==pRoot2.val:
return self.Traversal(pRoot1.left, pRoot2.right) and self.Traversal(pRoot1.right, pRoot2.left)
else:
return False
调用函数写在内部,注意调用的位置
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
def Traversal(pRoot1,pRoot2):
if not pRoot1 and not pRoot2:
return True
elif pRoot1 and pRoot2 and pRoot1.val==pRoot2.val:
return Traversal(pRoot1.left, pRoot2.right) and Traversal(pRoot1.right, pRoot2.left)
else:
return False
return Traversal(pRoot.left,pRoot.right)#在外层最后return,函数内是按步骤运行