100. Same Tree
1 题目
-
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / / 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / 2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1 / / 2 1 1 2 [1,2,1], [1,1,2] Output: false
2 解题 && 思路
对2棵树分别做前序遍历,然后把前序的字符串比较。注意左右子树是空,需要特殊标记。
3. 实现
# 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 dlr(self,tree,dirlist):
if tree is None :
return
if tree.left is not None :
self.dlr(tree.left,dirlist)
else:
dirlist.append(-2)
dirlist.append(tree.val)
if tree.right is not None :
self.dlr(tree.right,dirlist)
else:
dirlist.append(-1)
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
p_list = []
q_list = []
self.dlr(p,p_list)
self.dlr(q,q_list)
p_str=""
q_str=""
for e in p_list:
p_str = p_str+str(e)
for e in q_list:
q_str = q_str+str(e)
return p_str == q_str