forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBinaryTreeToLinkedList.java
More file actions
53 lines (43 loc) · 1.28 KB
/
FlattenBinaryTreeToLinkedList.java
File metadata and controls
53 lines (43 loc) · 1.28 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
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class FlattenBinaryTreeToLinkedList {
/**
* 非递归,先序遍历一遍,再串起来
*/
public void flatten(TreeNode root) {
Stack<TreeNode> stack = new Stack();
List<TreeNode> list = new ArrayList<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
list.add(root);
stack.push(root);
root = root.left;
} else {
root = stack.pop().right;
}
}
for (int i = 0; i < list.size() - 1; i++) {
list.get(i).left = null;
list.get(i).right = list.get(i + 1);
}
}
public void flatten2(TreeNode root) {
helper(root);
}
public TreeNode helper(TreeNode root) {
if (root == null) {
return null;
}
TreeNode right = root.right;
TreeNode leftTail = null, rightTail = null;
if (root.left != null) {
leftTail = helper(root.left);
root.right = root.left;
root.left = null;
leftTail.right = right;
}
rightTail = helper(right);
return rightTail != null ? rightTail : leftTail;
}
}