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.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7
8public class Solution {
9 public void flatten(TreeNode root) {
10 if (root == null) return;
11 TreeNode left = root.left;
12 TreeNode right = root.right;
13
14 root.left = null;
15 flatten(left);
16 flatten(right);
17
18 root.right = left;
19 TreeNode curr = root;
20 while (curr.right != null) {
21 curr = curr.right;
22 }
23 curr.right = right;
24 }
25}
This Java solution similarly utilizes recursion to adjust the tree into a flattened linked list. It handles the left and right subtrees separately and then links them using iteration to adjust the right pointers.
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.
1import java.util.Stack;
2
3class TreeNode {
4 int val;
5 TreeNode left;
6 TreeNode right;
7 TreeNode(int x) { val = x; }
8}
9
10public class Solution {
11 public void flatten(TreeNode root) {
12 if (root == null) return;
13 Stack<TreeNode> stack = new Stack<>();
14 stack.push(root);
15
16 while (!stack.isEmpty()) {
17 TreeNode current = stack.pop();
18
19 if (current.right != null) {
20 stack.push(current.right);
21 }
22 if (current.left != null) {
23 stack.push(current.left);
24 }
25
26 if (!stack.isEmpty()) {
27 current.right = stack.peek();
28 }
29 current.left = null;
30 }
31 }
32}
This Java solution efficiently uses a Stack for iterative pre-order traversal. Nodes are handled without recursion, effectively redirecting pointers to create the linked list.