Problem
Given the roots of two binary trees p and q, 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.
Algorithm
Recursion. If two trees are structurally identical for all the sub-trees, the node values are same and the left, right sub-tree are all structurally identical.
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q :
return True
print(p, q)
if (p and not q) or (not p and q) or (p.val != q.val) :
return False
if not self.isSameTree(p.left, q.left) :
return False
if not self.isSameTree(p.right, q.right) :
return False
return True
该博客讨论了如何通过递归算法判断两棵二叉树是否结构相同。当两棵树的所有子树在结构上完全一致且节点值相等时,它们被认为是相同的。给出的Python代码实现了一个`isSameTree`函数,首先检查根节点是否存在,然后比较节点值和左、右子树的结构。如果所有条件都满足,则返回True,否则返回False。
388

被折叠的 条评论
为什么被折叠?



