100. 相同的树

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

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

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if  (not p and q )or (p and not q )or( p.val!=q.val):
            return False
        return self.isSameTree(p.left,q.left)and self.isSameTree(p.right,q.right)

简单的递归解决问题,就是遍历一遍二叉树,看看对应的每个节点是否相等就Ok.

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

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        temp=[p,q]
        while temp :
            a1=temp.pop()
            a2=temp.pop()
            if not a1 and not a2:
                continue 
            if a1 and a2 and a1.val==a2.val:
                temp.append(a1.left)
                temp.append(a2.left)
                temp.append(a1.right)
                temp.append(a2.right)
            else:
                return False
        return True

迭代法,从右边到左边,也是深度遍历。

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

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        temp=[p,q]
        while temp :
            a1=temp.pop(0)
            a2=temp.pop(0)
            if not a1 and not a2:
                continue 
            if a1 and a2 and a1.val==a2.val:
                temp.append(a1.left)
                temp.append(a2.left)
                temp.append(a1.right)
                temp.append(a2.right)
            else:
                return False
        return True
  • 经马老师指导明白了这个地方,之前一直想的有点问题
  • 不得不说利用队列来实现层序遍历确实这个想法很不错
  • 利用队列实现层序遍历,

二刷

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

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val==q.val:
            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
        else:
            return False

你可能感兴趣的:(算法,数据结构与算法课程)