算法
(DPS) $O(n)$
先判断树的根的值是否相同,若相同,判断子树是否相同
Java 代码
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Python 代码
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p == None and q == None: return True
if p and q and p.val == q.val:
return self.isSameTree(p.left, q.left) and \
self.isSameTree(p.right, q.right)
return False