Same Tree
Structural recursion — both null OK; one null fails; equal values + recurse left and right.
2 min read
tree dfs recursion
Problem#
Return true iff two binary trees are structurally identical and have the same node values.
Examples#
[1,2,3],[1,2,3]→true.[1,2],[1,null,2]→false;[1,2,1],[1,1,2]→false.
Constraints#
0 <= nodes <= 100.
Approach#
Recursion: both null → equal; one null → not equal; values differ → not equal; else recurse on children.
Solution#
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
class Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { if (!p && !q) return true; if (!p || !q) return false; return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }};func isSameTree(p *TreeNode, q *TreeNode) bool { if p == nil && q == nil { return true } if p == nil || q == nil { return false } return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)}from typing import Optional
class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: if not p and not q: return True if not p or not q: return False return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)function isSameTree(p, q) { if (!p && !q) return true; if (!p || !q) return false; return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);}class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null || q == null) return false; return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }}function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { if (p === null && q === null) return true; if (p === null || q === null) return false; return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);}Editorial#
Three cases at every recursive call cover all possibilities for the pair. The order of the children matters — (left, left) and (right, right), not crosswise.
Complexity#
- Time:
O(n). - Space:
O(h)recursion (worst-caseO(n)).
Concept revision#
Related#