leetcode之Same Tree(100)

题目:

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true

示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

示例 3:

输入:       1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出: false

python代码1:

class Solution(object):
    def isSameTree(self, p, q):
        if p and q:
            return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        return p == q

python代码2:

class Solution(object):
    def isSameTree(self, p, q):
        stack = [(p, q)]
        while stack:
            p, q = stack.pop()
            if p == None and q == None:
                continue
            if p == None or q == None:
                return False
            if p.val == q.val:
                stack.append((p.right, q.right))
                stack.append((p.left, q.left))
            else:
                return False
        return True

python代码3:

class Solution(object):
    def isSameTree(self, p, q):
        queue = [(p, q)]
        while len(queue) != 0:
            p, q = queue.pop()
            if p == None and q == None:
                continue
            if p == None or q == None:
                return False
            if p.val == q.val:
                queue.insert(0, (p.left, q.left))
                queue.insert(0, (p.right, q.right))
            else:
                return False
        return True

python代码4:

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

心得:本体考察数据结构树的基本知识,属于基础题,第一种方法采用了深度优先搜索,用递归的方法遍历树,第二种方法非递归,用栈保存数据,第三种方法应用了队列来记录信息,采用广度优先搜索的方法。代码易读,读者有问题可以私信博主~

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/80331038