-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFlattenBinaryTreeToLinkedList.java
More file actions
73 lines (68 loc) · 2.02 KB
/
FlattenBinaryTreeToLinkedList.java
File metadata and controls
73 lines (68 loc) · 2.02 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class FlattenBinaryTreeToLinkedList {
// Recursive solution
// O(n) time and O(n) space
private static TreeNode flattenRecursive(TreeNode root) {
if (root == null) {
return null;
}
TreeNode leftTail = flattenRecursive(root.left);
TreeNode rightTail = flattenRecursive(root.right);
if (leftTail != null) {
leftTail.right = root.right;
root.right = root.left;
}
root.left = null;
rightTail = (rightTail == null) ? leftTail : rightTail;
return (root.right == null) ? root : rightTail;
}
public void flatten0(TreeNode root) {
flattenRecursive(root);
}
//Iterative solution using stack
public void flatten1(TreeNode root) {
if (root == null) {
return;
}
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
TreeNode pre = null;
while(!stack.isEmpty()) {
TreeNode cur = stack.pop();
if (pre != null) {
pre.right = cur;
pre.left = null;
}
pre = cur;
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
}
//Iterative solution
//O(n) time and O(1) space
public void flatten(TreeNode root) {
for(TreeNode cur = root; cur != null; cur = cur.right) {
if (cur.left != null) {
if (cur.right != null) {
TreeNode next = cur.left;
for(; next.right != null; next = next.right);
next.right = cur.right;
}
cur.right = cur.left;
cur.left = null;
}
}
}
}