您的位置:首页 > 编程语言 > Python开发

[leetCode By Python]100. Same Tree

2018-02-01 23:07 393 查看
题目:

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

代码+调试:

# 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 isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p==q==None:
return True
if p and q and p.val ==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)#利用递归的方法
return False

if __name__ == '__main__':
l1_1 = TreeNode(1)
l1_2 = TreeNode(2)
l1_3 = TreeNode(3)

l1_1.left = l1_2
l1_1.right = l1_3

l2_1 = TreeNode(1)
l2_2 = TreeNode(2)
l2_3 = TreeNode(3)

l2_1.left = l2_2
l2_1.right = l2_3

l3 = Solution().isSameTree(l1_1,l2_1)
print l3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: