Skip to content

Commit f0edd0f

Browse files
committed
feat: add another js solution to lc problem: no.426
1 parent 05e653c commit f0edd0f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/Solution.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,42 @@ var treeToDoublyList = function (root) {
2727
pre.right = head;
2828
return head;
2929
};
30+
31+
//solution 2
32+
/**
33+
* // Definition for a Node.
34+
* function Node(val, left, right) {
35+
* this.val = val;
36+
* this.left = left;
37+
* this.right = right;
38+
* };
39+
*/
40+
41+
/**
42+
* @param {Node} root
43+
* @return {Node}
44+
*/
45+
var treeToDoublyList = function (root) {
46+
if (!root) return;
47+
let stk = [];
48+
let cur = root;
49+
let pre, head;
50+
while (cur || stk.length) {
51+
while (cur) {
52+
stk.push(cur);
53+
cur = cur.left;
54+
}
55+
let top = stk.pop();
56+
if (pre) {
57+
pre.right = top;
58+
top.left = pre;
59+
} else {
60+
head = top;
61+
}
62+
pre = top;
63+
cur = top.right;
64+
}
65+
pre.right = head;
66+
head.left = pre;
67+
return head;
68+
};

0 commit comments

Comments
 (0)