知识点:树
题目描述:
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:
使用递归法,对比该二叉树的左右子节点。
详解:
# -*- 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, L, R):
if not L and not R:
return True
if not L or not R:
return False
if L.val == R.val:
if self.compare(L.left, R.right) and self.compare(L.right, R.left):
return True
return False