首页 > 代码库 > Leetcode 100. Same Tree

Leetcode 100. Same Tree

思路1: 递归,如果 p = q, 那么判段 sameTree(p.left)==sameTree(q.left) and sameTree(p.right) = sameTree(q.right)

 1 class Solution(object):
 2     def isSameTree(self, p, q):
 3         """
 4         :type p: TreeNode
 5         :type q: TreeNode
 6         :rtype: bool
 7         """
 8         if not p and not q:
 9             return True
10         
11         if p and q:    
12             if p.val == q.val:
13                 return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
14             else:
15                 return False
16         
17         return False

 

思路二: 如果两个树相同,说明按照一定的方式遍历这两个树,应该得到一样的结果。这里用的方法是使用stack来实现先序遍历(pre-order)。注意pre-order遍历时是,root -> root.left -> root.right。所以push进stack的时候应该先push root.right再push root.left。

 1 class Solution(object):
 2     def isSameTree(self, p, q):
 3         """
 4         :type p: TreeNode
 5         :type q: TreeNode
 6         :rtype: bool
 7         """
 8         if p == None and q == None:
 9             return True
10         
11         stack = [(p, q)]
12         
13         while stack:
14             l, r = stack.pop()
15             
16             if l == None and r == None:
17                 continue
18             elif l and r and l.val == r.val:
19 
20                 stack.append((l.right, r.right)) 
21 
22                 stack.append((l.left, r.left))              
23             else:
24                 return False
25         
26         return True

 

Leetcode 100. Same Tree