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
My code:
# 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, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
label=self.Compare(p,q)
return bool(label)
def Compare(self,p,q):
if p==None and q==None:
return True
elif p!=None and q==None:
return False
elif q!=None and p==None:
return False
if p.val!=q.val:
return False
l1=p.left
l2=q.left
if l1==None and l2!=None:
return False
if l1!=None and l2==None:
return False
label_l=True
if l1!=None and l2!=None:
if l1.val!=l2.val:
return False
label1=self.Compare(l1.left,l2.left)
label2=self.Compare(l1.right,l2.right)
label_l=label1 and label2
label_r=True
if label_l:
r1=p.right
r2=q.right
if r1==None and r2!=None:
return False
if r1!=None and r2==None:
return False
if r1!=None and r2!=None:
if r1.val!=r2.val:
return False
label1=self.Compare(r1.left,r2.left)
label2=self.Compare(r1.right,r2.right)
label_r=label1 and label2
return label_l and label_r
Solution: https://leetcode.com/problems/same-tree/