Easy
遍历树,比较两棵树的子树
None
时无法向下递归,递归终止。
None
时,说明遍历了所有节点,且当前节点也相同,返回True
None
,另一个节点不为None
,说明最终节点不相同,返回False
以上,尝试一下代码,AC!
python3
class Solution:
def helper(self, node1, node2):
if node1 is None and node2 is not None:
return False
elif node2 is None and node1 is not None:
return False
elif node1 is None and node2 is None:
return True
if node1.val != node2.val:
return False
return self.helper(node1.left, node2.left) and self.helper(node1.right ,node2.right)
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
return self.helper(p,q)