leetcode -- Same Tree -- 简单重点

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

我的方法是用dfs来做

my code:

class Solution(object):
    def isSameTree(self, p, q):
        """ :type p: TreeNode :type q: TreeNode :rtype: bool """

        if not q and not p: return True

        if not q or not p: return False

        stack1, stack2 = [], []

        while stack1 or stack2 or p or q:

            if p:
                stack1.append(p)
                p = p.left
            else:
                p = stack1.pop()
                p = p.right

            if q:
                stack2.append(q)
                q = q.left
            else:
                q = stack2.pop()
                q = q.right

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

其实可以直接用recursive来做。http://www.cnblogs.com/zuoyuan/p/3747148.html

你可能感兴趣的:(LeetCode)