题目描述
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
思路
1) 如果同时root1,root2都没有了,返回true
2) 如果root1,root2任意一个还有,返回false
3) 如果root1,root2的值不相同,返回false
4) 分别去遍历root1.left==root2.right; root1.right==root2.left
# Definition for a binary tree node.
class TreeNode(object):def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = right
class Solution(object):def judge(self,root1,root2):if not root1 and not root2:return Trueif not root1 or not root2:return Falseif root1.val != root2.val:return Falsereturn self.judge(root1.left, root2.right) and self.judge(root1.right, root2.left)def isSymmetric(self, root):""":type root: TreeNode:rtype: bool"""if not root:return Truereturn self.judge(root,root)if __name__ == '__main__':s=Solution()root = TreeNode(1)node1 = TreeNode(2)node2 = TreeNode(2)root.left = node1root.right = node2node1.left = node1.right = node2.left = node2.right = Noneprint(s.isSymmetric(root))