Question
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.
Hide Tags Tree Depth-first Search
Analysis
It is similar as Symmetric Tree.
Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} p
# @param {TreeNode} q
# @return {boolean}
def isSameTree(self, p, q):
return self.helper(p,q)
def helper(self,root1,root2):
if root1==None and root2==None:
return True
if root1==None or root2==None:
return False
if root1.val!=root2.val:
return False
return self.helper(root1.left,root2.left) and self.helper(root1.right, root2.right)