快乐的LeetCode --- 相同的树

题目描述:

给定两个二叉树,编写一个函数来检验它们是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 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

解题思路1:

二叉树的前序遍历与题目中描述的顺序一致,但是目前受限于判断 [1,2][1,null,2]


代码1:

class Solution(object):
    def isSameTree(self, p, q):
        if p is not None and q is not None:
            return True
        stack1, output1 = [p], []
        stack2, output2 = [q], []         
         
        while  stack1:
            root1 = stack1.pop()
            if root1 is not None:
                output1.append(root1)
                if root1.right is not None:
                    stack1.append(root1.right)
                else:
                    stack1.append(null)
                if root1.left is not None:
                    stack1.append(root1.left)
                else:
                    stack1.append(null)
        
        while  stack2:
            root2 = stack2.pop()
            if root2 is not None:
                output2.append(root2)
                if root2.right is not None:
                    output2.append(root2.right)
                else:
                    stack2.append(null)
                if root2.left is not None:
                    output2.append(root2.left)
                else:
                    stack2.append(null)

        if output1 == output2:
            return True
        return False

解题思路2:

递归思路


代码2:

# 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 isSameTree(self, p, q):
        if not p and not q:
            return True
        if not p or not q:
            return False

        if p.val != q.val:   # 这里的写法不能是当二者相等就返回True,因为我们还需要判断接下来的情况
            return False

        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

题目来源:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值