Skip to content

Latest commit

 

History

History
30 lines (26 loc) · 1016 Bytes

File metadata and controls

30 lines (26 loc) · 1016 Bytes
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p && !q) return true;
        if(!p || !q) return false;
        if(p->val != q->val) return false;
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};

Time Complexity: O(n), where n is the number of nodes. In the worst case, we must compare every node of both trees (unless we find a mismatch early and return sooner).

Space Complexity: O(h), where h is the height of the tree. This comes from the recursion stack during the depth-first traversal. For a balanced tree, this is O(log n); for a skewed tree, it becomes O(n).