This approach involves a recursive pre-order traversal of the tree. The idea is to recursively flatten the left and right subtrees, then append the flattened left subtree between the root and the flattened right subtree.
The steps are as follows:
This leverage the pre-order traversal principle: Root → Left → Right
.
Time Complexity: O(n)
where n
is the number of nodes in the tree since each node is visited once.
Space Complexity: O(n)
due to the recursive call stack on an unbalanced tree.
1#include <stdio.h>
2
3struct TreeNode {
4 int val;
5 struct TreeNode *left;
6 struct TreeNode *right;
7};
8
9void flatten(struct TreeNode* root) {
10 if (!root) return;
11 struct TreeNode* left = root->left;
12 struct TreeNode* right = root->right;
13
14 root->left = NULL;
15 flatten(left);
16 flatten(right);
17
18 root->right = left;
19 struct TreeNode* current = root;
20 while (current->right) {
21 current = current->right;
22 }
23 current->right = right;
24}
This code defines a flatten
function for recursively transforming a binary tree into a linked list in pre-order format. It first flattens the left and right subtrees, then rearranges the pointers of the root node.
This approach simplifies the recursive method by using a stack to maintain state information. By using controlled use of stack structures, we can modify the tree iteratively.
The algorithm progresses with these steps:
This achieves similar logic as recursion but without directly using the call stack by using our custom stack for maintaining traversal state.
Time Complexity: O(n)
because every node is processed once.
Space Complexity: O(n)
, matching the worst-case stack usage when all nodes are in a single path.
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val)
3 this.left = (left===undefined ? null : left)
4 this.right = (right===undefined ? null : right)
5}
6
7var flatten = function(root) {
8 if (!root) return;
9 let stack = [root];
10
11 while (stack.length > 0) {
12 let current = stack.pop();
13
14 if (current.right !== null) {
15 stack.push(current.right);
16 }
17 if (current.left !== null) {
18 stack.push(current.left);
19 }
20
21 if (stack.length > 0) {
22 current.right = stack[stack.length - 1];
23 }
24 current.left = null;
25 }
26};
This JavaScript solution utilizes an iterative methodology to rearrange the tree into a single-right linked list form. The algorithm handles successor arrangement using a stack to safeguard node traversal order comparable to pre-order.