Leetcode: Same Tree

来源:互联网 发布:大数据培训课程有哪些 编辑:程序博客网 时间:2024/06/06 02:15

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 = Noneclass 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)


0 0
原创粉丝点击