请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def isSameTree(self,left,right): 9 if left != None and right != None: 10 if left.val != right.val: 11 return False 12 else: 13 return self.isSameTree(left.left,right.right) and self.isSameTree(left.right,right.left) 14 if left == None and right == None: 15 return True 16 else: 17 return False 18 19 def isSymmetrical(self, pRoot): 20 if pRoot == None: 21 return True 22 return self.isSameTree(pRoot.left,pRoot.right) 23 # write code here
Java版,leetcode地址:
1 class Solution { 2 public boolean isSameTrees(TreeNode left, TreeNode right) { 3 if (left == null && right == null) { 4 return true; 5 } else if (left != null && right != null) { 6 if (left.val != right.val) { 7 return false; 8 } else { 9 return isSameTrees(left.left, right.right) && isSameTrees(left.right, right.left); 10 } 11 } else { 12 return false; 13 } 14 } 15 16 public boolean isSymmetric(TreeNode root) { 17 if (root == null) { 18 return true; 19 } else { 20 return isSameTrees(root.left, root.right); 21 } 22 } 23 }