# LeetCode.100 相同的树（python解法）

LeetCode刷题记录 专栏收录该内容
62 篇文章 1 订阅

# 题目

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

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



输入:      1          1
/           \
2             2

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



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

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



# solution_1

# 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 p and q and p.val==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
return False


# solution_1

# 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:
stack = [(p,q)]
while stack:
a,b = stack.pop()
if not a and not b:
continue
if a and b and a.val == b.val:
stack.append((a.left,b.left))
stack.append((a.right,b.right))
else:
return False
return True


• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

10-11 27
03-17 1227
10-12 9
10-11 4