Q101 Symmetric Tree

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.
解题思路:

简单方法,就是复制一棵相同的数,然后比较左右结点是否满足对称树的条件。由于原函数只传入了一棵树的根节点,因此需要重新定义一个函数,可以传入两棵树的根节点,然后进行比较。

Python实现:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True
        return Solution.isMirror(self, root.left, root.right)
        

    def isMirror(self, p, q):
        if p == None and q == None: 
            return True
        if p != None and q != None and p.val == q.val:
            return Solution.isMirror(self, p.left, q.right) and Solution.isMirror(self, p.right, q.left)
        else:
            return False

你可能感兴趣的:(Q101 Symmetric Tree)