题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:
定义一个比较函数比较左右子树
1.左子树为空,返回右子树是否为空
2.右子树为空,返回false
3.左右节点的值不同,返回false
4.递归比较 左子树的右子树和右子树的左子树 and 右子树的左子树和左子树的右子树
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
return self.compare(pRoot.left,pRoot.right)
def compare(self,leftroot,rightroot):
if leftroot==None:
return rightroot==None
if rightroot==None:
return False
if leftroot.val!=rightroot.val:
return False
return self.compare(leftroot.right,rightroot.left) and self.compare(leftroot.left,rightroot.right)
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if (pRoot == null)
return true;
return comRoot(pRoot.left, pRoot.right);
}
boolean comRoot(TreeNode pLeft, TreeNode pRight)
{
if (pLeft == null) return pRight == null;
if (pRight == null) return false;
if (pLeft.val != pRight.val) return false;
return comRoot(pLeft.left, pRight.right) && comRoot(pLeft.right, pRight.left);
}
}