# 100. Same Tree [easy] (Python)

## 題目連結

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

## 題目原文

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

## 思路方法

### 思路一

``````# 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):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
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``````

### 思路二

``````# 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):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
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``````

### 思路三

``````# 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):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
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``````

PS: 新手刷LeetCode，新手寫部落格，寫錯了或者寫的不清楚還請幫忙指出，謝謝！