File tree 2 files changed +39
-1
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +39
-1
lines changed Original file line number Diff line number Diff line change 3
3
public class _426 {
4
4
5
5
public static class Solution1 {
6
+ /**
7
+ * Credit: https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/solutions/1494821/simplest-java-solution-with-explanation-inorder-traversal-in-place-no-dummy-node-needed/
8
+ */
6
9
Node head ;
7
10
Node tail ;
8
11
@@ -20,20 +23,25 @@ private void dfs(Node node) {
20
23
if (node == null ) {
21
24
return ;
22
25
}
26
+ //we traverse all the way to the most bottom left leaf node first
23
27
dfs (node .left );
28
+ //we only need to assign head once, i.e. when it's not assigned, we'll assign the most bottom left leaf node to head
24
29
if (head == null ) {
25
30
head = node ;
26
31
}
32
+ //if the tail is already assigned, which should be all of the cases except when it's just finding the most bottom left leaf
33
+ // attach current node to tail's right, assign tail to current node's left
27
34
if (tail != null ) {
28
35
tail .right = node ;
29
36
node .left = tail ;
30
37
}
38
+ //then always assign the current node to be the new tail
31
39
tail = node ;
32
40
dfs (node .right );
33
41
}
34
42
}
35
43
36
- private static class Node {
44
+ public static class Node {
37
45
public int val ;
38
46
public Node left ;
39
47
public Node right ;
Original file line number Diff line number Diff line change
1
+ package com .fishercoder ;
2
+
3
+ import com .fishercoder .solutions ._426 ;
4
+ import org .junit .jupiter .api .BeforeEach ;
5
+ import org .junit .jupiter .api .Test ;
6
+
7
+ public class _426Test {
8
+ private static _426 .Solution1 solution1 ;
9
+
10
+ @ BeforeEach
11
+ public void setup () {
12
+ solution1 = new _426 .Solution1 ();
13
+ }
14
+
15
+ @ Test
16
+ public void test1 () {
17
+ _426 .Node node1 = new _426 .Node (1 );
18
+ _426 .Node node3 = new _426 .Node (3 );
19
+ _426 .Node node5 = new _426 .Node (5 );
20
+ _426 .Node node2 = new _426 .Node (2 );
21
+ node2 .left = node1 ;
22
+ node2 .right = node3 ;
23
+ _426 .Node node4 = new _426 .Node (4 );
24
+ node4 .left = node2 ;
25
+ node4 .right = node5 ;
26
+ _426 .Node actual = solution1 .treeToDoublyList (node4 );
27
+ System .out .println ("Finished." );
28
+ }
29
+
30
+ }
You can’t perform that action at this time.
0 commit comments