File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -27,3 +27,42 @@ var treeToDoublyList = function (root) {
27
27
pre . right = head ;
28
28
return head ;
29
29
} ;
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
+ } ;
You can’t perform that action at this time.
0 commit comments