【LEETCODE】101-Symmetric Tree

来源:互联网 发布:黑马播放器 for mac 编辑:程序博客网 时间:2024/05/20 08:25

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

For example, this binary tree is symmetric:

    1

   / \

  2   2

 / \ / \

3  4 4  3


But the following is not:

    1

   / \

  2   2

   \   \

   3    3


Note:

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


confused what "{1,#,2,3}" means?

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1

  / \

 2   3

    /

   4

    \

     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".


思路:

当 root.left == root.right 时,再去判断 root.left.left == root.right.right 和 root.left.right == root.right.left (只为记号,并不存在root.left.right之说)

然后再去递归判断 root.left.left vs root.right.right 作为root的时候,及 root.left.right vs root.right.left 作为root的时候


# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):        def compare(self,p,q):         #当两个node相等时,比较两个node作为根时的子树是否对称        if p == q == None:            return True        elif p and q and p.val == q.val:        #[2,2]              return self.compare(p.left,q.right) and self.compare(p.right,q.left)      #[2,3,4] vs [2,4,3]        else:            return False        def isSymmetric(self, root):        """        :type root: TreeNode        :rtype: bool        """                if root is None:            return True        else:                     #[1]            return self.compare(root.left,root.right)     #对称,需要比较两个root,所以需要写一个辅助函数



0 0
原创粉丝点击