Skip to content

Commit 8ee3d92

Browse files
committed
Add solution #426
1 parent 51ac1cc commit 8ee3d92

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,7 @@
414414
423|[Reconstruct Original Digits from English](./solutions/0423-reconstruct-original-digits-from-english.js)|Medium|
415415
424|[Longest Repeating Character Replacement](./solutions/0424-longest-repeating-character-replacement.js)|Medium|
416416
425|[Word Squares](./solutions/0425-word-squares.js)|Hard|
417+
426|[Convert Binary Search Tree to Sorted Doubly Linked List](./solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js)|Medium|
417418
427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium|
418419
429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium|
419420
430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* 426. Convert Binary Search Tree to Sorted Doubly Linked List
3+
* https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
4+
* Difficulty: Medium
5+
*
6+
* Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
7+
*
8+
* You can think of the left and right pointers as synonymous to the predecessor and successor
9+
* pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the
10+
* first element is the last element, and the successor of the last element is the first element.
11+
*
12+
* We want to do the transformation in place. After the transformation, the left pointer of the
13+
* tree node should point to its predecessor, and the right pointer should point to its successor.
14+
* You should return the pointer to the smallest element of the linked list.
15+
*/
16+
17+
/**
18+
* // Definition for a _Node.
19+
* function _Node(val, left, right) {
20+
* this.val = val;
21+
* this.left = left;
22+
* this.right = right;
23+
* };
24+
*/
25+
26+
/**
27+
* @param {_Node} root
28+
* @return {_Node}
29+
*/
30+
var treeToDoublyList = function(root) {
31+
if (!root) return null;
32+
33+
let first = null;
34+
let last = null;
35+
36+
inorder(root);
37+
38+
last.right = first;
39+
first.left = last;
40+
41+
return first;
42+
43+
function inorder(node) {
44+
if (!node) return;
45+
46+
inorder(node.left);
47+
48+
if (last) {
49+
last.right = node;
50+
node.left = last;
51+
} else {
52+
first = node;
53+
}
54+
last = node;
55+
56+
inorder(node.right);
57+
}
58+
};

0 commit comments

Comments
 (0)