首页 > 代码库 > leetcode:Same Tree【Python版】

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 node10     # @param q, a tree node11     # @return a boolean12     def isSameTree(self, p, q):13         if p==None and q==None:14             return True15         if p==None or q==None:16             return False17         v = p.val==q.val18         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

 

leetcode:Same Tree【Python版】