-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path114.java
More file actions
80 lines (71 loc) · 1.99 KB
/
114.java
File metadata and controls
80 lines (71 loc) · 1.99 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
74
75
76
77
78
79
80
__________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode prev;
public void flatten(TreeNode root) {
//base case
if(root == null){
return;
}
prev = null;
//run it in recursion pre-order
flattenTree(root);
}
//Function to flatten tree with pre-order traversal
public void flattenTree(TreeNode current){
if(current == null){
return;
}
//start addiing current to the right of the prev
if(prev != null){
prev.right = current;
prev.left = null;
}
prev = current;
//get all nodes form left --> right and add to the prev
TreeNode right = current.right;
flattenTree(current.left);
flattenTree(right);
}
}
__________________________________________________________________________________________________
sample 34252 kb submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 04/03/2019
// Runtime: 0 ms, beat 100%
class Solution {
public void flatten(TreeNode root) {
if (root == null) {
return;
}
flattenHelper(root, new TreeNode[] {null});
}
private void flattenHelper(TreeNode root, TreeNode[] prev) {
if (root == null) {
return;
}
flattenHelper(root.right, prev);
flattenHelper(root.left, prev);
root.right = prev[0];
root.left = null;
prev[0] = root;
}
}
__________________________________________________________________________________________________