LeetCode 114. Flatten Binary Tree to Linked List 3 Approaches: PreOrder, Iteration and Recursion
By Long Luo
This article is the solution Image Explanation to Understand the Recursion Solution of Problem 114. Flatten Binary Tree to Linked List .
The Binary Tree Traversal Algorithms can be find here Tree Traversal Algorithms: PreOrder, InOrder and PostOrder .
We can use DFS to traversal the binary tree.
PreOrder + List
It’s easy to find that the flatten tree is the PreOrder of the tree. We can preorder the tree and store the TreeNodes in a List.
Traversal the list, make the current node as the preNode’s right node.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public void flatten(TreeNode root) {
if (root == null) {
return;
}
List<TreeNode> nodeList = new ArrayList<>();
preOrder(root, nodeList);
int n = nodeList.size();
for (int i = 1; i < n; i++) {
TreeNode preNode = nodeList.get(i - 1);
TreeNode currNode = nodeList.get(i);
preNode.left = null;
preNode.right = currNode;
}
}
public void preOrder(TreeNode root, List<TreeNode> nodeList) {
if (root == null) {
return;
}
nodeList.add(root);
preOrder(root.left, nodeList);
preOrder(root.right, nodeList);
}
We can also traversal the tree iteratively with a Stack:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public void flatten(TreeNode root) {
if (root == null) {
return;
}
List<TreeNode> nodeList = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
while (root != null || !stk.empty()) {
while (root != null) {
nodeList.add(root);
stk.push(root);
root = root.left;
}
root = stk.pop();
root = root.right;
}
int len = nodeList.size();
for (int i = 1; i < len; i++) {
TreeNode preNode = nodeList.get(i - 1);
TreeNode currNode = nodeList.get(i);
preNode.left = null;
preNode.right = currNode;
}
}
Analysis
- Time Complexity: \(O(n)\).
- Space Complexity: \(O(n)\).