[leetcode]Same Tree @ Python

时间:2014-05-26 10:30:17   收藏:0   阅读:289

原题地址:https://oj.leetcode.com/problems/same-tree/

题意:判断两棵树是否是同一棵树。

解题思路:这题比较简单。用递归来做。首先判断两个根节点的值是否相同,如果相同,递归判断根的左右子树。

代码:

bubuko.com,布布扣
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param p, a tree node
    # @param q, a tree node
    # @return a boolean
    def isSameTree(self, p, q):
        if p == None and 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
bubuko.com,布布扣

 

[leetcode]Same Tree @ Python,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!