Skip to content

Commit b95c4e1

Browse files
update 426
1 parent ffeee6a commit b95c4e1

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_426.java

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
public class _426 {
44

55
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+
*/
69
Node head;
710
Node tail;
811

@@ -20,20 +23,25 @@ private void dfs(Node node) {
2023
if (node == null) {
2124
return;
2225
}
26+
//we traverse all the way to the most bottom left leaf node first
2327
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
2429
if (head == null) {
2530
head = node;
2631
}
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
2734
if (tail != null) {
2835
tail.right = node;
2936
node.left = tail;
3037
}
38+
//then always assign the current node to be the new tail
3139
tail = node;
3240
dfs(node.right);
3341
}
3442
}
3543

36-
private static class Node {
44+
public static class Node {
3745
public int val;
3846
public Node left;
3947
public Node right;

Diff for: src/test/java/com/fishercoder/_426Test.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

0 commit comments

Comments
 (0)