[LeetCode] 100. Same Tree_Easy tag: DFS
2018-08-07 04:31 Johnson_强生仔仔 阅读(193) 评论(0) 收藏 举报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
思路基本的DFS, 都空, 为True, 都不为空, 判断value一样, 并且recursive children, 否则False
1. Constraints
1) 可以都为None => True
2. Ideas
DFS O(n)
3. Code
class Solution: def sameTree(self, p, q): if not p and not q: return True if p and q and p.val == q.val: return self.sameTree(p.left, q.left) and self.sameTree(p.right, q.right) return False
浙公网安备 33010602011771号