相同的树
中英题面
给定两个二叉树,写一个函数来检查它们是否相同。
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.
示例 1:
输入 : 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
示例 2:
输入 : 1 1 / \ 2 2 [1,2], [1,null,2] 输出: false
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
例 3:
输入 : 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
输出: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
算法
递归判断,若当前结点都不为空且左右子树都相同或当前结点都为空时,则两棵当前子树相同,否则不同。
代码
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 def isSameTree(self, p, q): 10 """ 11 :type p: TreeNode 12 :type q: TreeNode 13 :rtype: bool 14 """ 15 if (p and q): 16 return p.val == q.val and Solution.isSameTree(self, p.left, q.left) and Solution.isSameTree(self, p.right, q.right) 17 elif (p or q): 18 return False 19 return True