leetcode -- Symmetric Tree -- 简单重点

https://leetcode.com/problems/symmetric-tree/

我的思路就是左dfs和右dfs的结果一样。

class Solution(object):



    def isSymmetric(self, root):
        """ :type root: TreeNode :rtype: bool """

        stack1, stack2 = [], []
        res1, res2 = [], []
        node1, node2 = root, root
        while stack1 or stack2 or node1 or node2 :
            if node1:
                stack1.append(node1)
                node1 = node1.left
            else:
                node1 = stack1.pop()
                if node1 == root:
                    node1 = None
                else:
                    node1 = node1.right

            if node2:
                stack2.append(node2)
                node2 = node2.right
            else:
                node2 = stack2.pop()
                if node2 == root:
                    node2 = None
                else:
                    node2 = node2.left

            if [x.val for x in stack1] != [x.val for x in stack2]:
                return False

        return True

最简单的的办法是用recursive。 ref: http://www.cnblogs.com/zuoyuan/p/3747174.html

class Solution(object):


    def issym(self, p, q):

        if  p  == None and q == None: return True

        if p and q and p.val == q.val:
            return self.issym(p.left, q.right) and self.issym(p.right, q.left)
        return False

    def isSymmetric(self, root):
        """ :type root: TreeNode :rtype: bool """
        if root:
            return self.issym(root.left, root.right)
        return True

你可能感兴趣的:(LeetCode)