-
Notifications
You must be signed in to change notification settings - Fork 171
/
FlattenBinaryTreetoLinkedList.java
81 lines (79 loc) · 2.06 KB
/
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
/*
Author: Andy, [email protected]
Date: Jan 28, 2015
Problem: Flatten Binary Tree to Linked List
Difficulty: Medium
Source: https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/
Notes:
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.
Solution: Recursion. Return the last element of the flattened sub-tree.
*/
/**
* 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) {
flatten_3(root);
}
public void flatten_1(TreeNode root) {
if (root == null) return;
flatten_1(root.left);
flatten_1(root.right);
if (root.left == null) return;
TreeNode node = root.left;
while (node.right != null) node = node.right;
node.right = root.right;
root.right = root.left;
root.left = null;
}
public void flatten_2(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(root);
while (stk.empty() == false) {
TreeNode cur = stk.pop();
if (cur.right != null) stk.push(cur.right);
if (cur.left != null) stk.push(cur.left);
cur.left = null;
cur.right = stk.empty() == true ? null : stk.peek();
}
}
public TreeNode flattenRe3(TreeNode root, TreeNode tail) {
if (root == null) return tail;
root.right = flattenRe3(root.left, flattenRe3(root.right, tail));
root.left = null;
return root;
}
public void flatten_3(TreeNode root) {
if (root == null) return;
flattenRe3(root, null);
}
}