Symmetric Tree in python

问题链接

https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627/

解题思路

方法一

遍历while循环
错误点:在while循环内,将qr写成了ql,导致队列变空
待改进点:使用了Queue方法,导致效率很慢

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import Queue

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        
        ql = Queue.Queue()
        qr = Queue.Queue()
        
        ql.put(root.left, False)
        qr.put(root.right, False)
        
        while not ql.empty() and not qr.empty():
            nl = ql.get(False)
            nr = qr.get(False)
            
            if (nl and not nr) or (not nl and nr):
                return False
            
            if nl:
                if nl.val != nr.val:
                    return False
                ql.put(nl.left, False)
                ql.put(nl.right, False)
                qr.put(nr.right, False)
                qr.put(nr.left, False)
        
        return True

方法二

递归方法
跟迭代方法类似,注意左右次序

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

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.sym(root.left, root.right) if root else True
    
    def sym(self, left, right):
        if not left and not right:
            return True
        if not left:
            return False
        if not right:
            return False
        
        if left.val != right.val:
            return False
        return self.sym(left.left, right.right) and self.sym(left.right, right.left)

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