您的位置:首页 > 其它

Leetcode: Same Tree

2015-05-15 03:08 316 查看

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

[code]# 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: