1. Preorder Array Collection + Relinking
Intuition
Traverse tree in standard preorder and push pointers to an array. Then loop from 0 to n-2 setting nodes[i].right = nodes[i+1] and nodes[i].left = null.
When to apply: Basic baseline check.
Algorithm
- Step 1: Traverse tree preorder, storing TreeNode* in list.
- Step 2: Iterate through list from 0 to list.size() - 2.
- Step 3: list[i].right = list[i + 1]; list[i].left = null.
- Step 4: list.back().left = list.back().right = null.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void preorder(TreeNode* node, vector<TreeNode*>& nodes) { if (!node) return; nodes.push_back(node); preorder(node->left, nodes); preorder(node->right, nodes); } void flatten(TreeNode* root) { if (!root) return; vector<TreeNode*> nodes; preorder(root, nodes); for (int i = 0; i < (int)nodes.size() - 1; ++i) { nodes[i]->left = nullptr; nodes[i]->right = nodes[i + 1]; } nodes.back()->left = nullptr; nodes.back()->right = nullptr; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Preorder traversal takes O(n); relinking takes O(n). - Space complexity:
O(n)— Array stores n node references.