leetcode:Same Tree【Python版】

1、p或q为None的情况用开始的两个if语句进行判断;

2、类中递归调用函数需要使用self进行调用;

3、代码很简洁,最后几行通过同时为None和同时非None的条件进行判断;

 1 # Definition for a  binary tree node
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     # @param p, a tree node
10     # @param q, a tree node
11     # @return a boolean
12     def isSameTree(self, p, q):
13         if p==None and q==None:
14             return True
15         if p==None or q==None:
16             return False
17         v = p.val==q.val
18         l = (p.left==None and q.left==None)
19         r = (p.right==None and q.right==None)
20         if p.left!=None and q.left!=None:
21             l = self.isSameTree(p.left,q.left)
22         if p.right!=None and q.right!=None:
23             r = self.isSameTree(p.right,q.right)
24         return v and l and r

 

posted @ 2014-10-18 23:57  ZH奶酪  阅读(460)  评论(0编辑  收藏  举报