LeetCode 101 Symmetric Tree

来源:互联网 发布:腾讯的大数据应用 编辑:程序博客网 时间:2024/06/10 02:21

题目:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1   / \  2   2 / \ / \3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1   / \  2   2   \   \   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

题目链接

题意:

给一个二叉树,判断这棵树是不是关于中心轴镜像对称的,首先,要搞清楚镜像对称的特点,即左手为右手,右手为左手,,,在这颗树的判断中就是对应的两个节点中的一个左节点等于与其对应的另一个节点的右节点,另一个节点也相互对应。

代码如下:

class Solution(object):    def isSymmetric(self, root):                def doubleTreeNode(node1, node2):            if node1 == None and node2 == None:                return True            elif node1 == None or node2 == None:                return False            else:                return node1.val == node2.val \                and doubleTreeNode(node1.left, node2.right) \                and doubleTreeNode(node1.right, node2.left)        return doubleTreeNode(root, root)