1. Tree Serialization and Comparison
Intuition
Serialize p and q using preorder traversal with # for nulls, then compare strings.
When to apply: Basic baseline check.
Algorithm
- Step 1: Serialize tree p to string s1.
- Step 2: Serialize tree q to string s2.
- Step 3: Return s1 == s2.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void serialize(TreeNode* root, string& s) { if (!root) { s += "#,"; return; } s += to_string(root->val) + ","; serialize(root->left, s); serialize(root->right, s); } bool isSameTree(TreeNode* p, TreeNode* q) { string s1 = "", s2 = ""; serialize(p, s1); serialize(q, s2); return s1 == s2; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n + m)— Builds full string serialization of both trees. - Space complexity:
O(n + m)— String memory O(n + m).