-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path114_FlattenBinaryTreeToLinkedList.java
84 lines (78 loc) · 2 KB
/
114_FlattenBinaryTreeToLinkedList.java
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
74
75
76
77
78
79
80
81
82
83
84
/*
* Given a binary tree, flatten it to a linked list in-place.
* For example,
* Given
*
* 1
* / \
* 2 5
* / \ \
* 3 4 6
* The flattened tree should look like:
* 1
* \
* 2
* \
* 3
* \
* 4
* \
* 5
* \
* 6
* Hints:
* If you notice carefully in the flattened tree, each node's right child points
* to the next node of a pre-order traversal.
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
if(root == null) return;
flatten(root.left);
flatten(root.right);
TreeNode right = root.right;
if(root.left != null) {
root.right = root.left;
root.left = null;
while(root.right != null) root = root.right;
root.right = right;
}
}
}
/***************************** updated 2013/12/29 ****************************/
public void flatten(TreeNode root) {
flatten(root, null);
}
public TreeNode flatten(TreeNode root, TreeNode tail) {
if(root == null)
return tail;
root.right = flatten(root.left, flatten(root.right, tail));
root.left = null;
return root;
}
/*****************************************************************************/
public void flatten(TreeNode root) {
if(root == null)
return ;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode cur = stack.pop();
if(cur.right != null)
stack.push(cur.right);
if(cur.left != null)
stack.push(cur.left);
cur.left = null;
if(!stack.isEmpty())
cur.right = stack.peek();
}
}
}