Skip to content

Commit c4e12a6

Browse files
committed
Add solution #114
1 parent 999e7a5 commit c4e12a6

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@
108108
111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy|
109109
112|[Path Sum](./0112-path-sum.js)|Easy|
110110
113|[Path Sum II](./0113-path-sum-ii.js)|Medium|
111+
114|[Flatten Binary Tree to Linked List](./0114-flatten-binary-tree-to-linked-list.js)|Medium|
111112
116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium|
112113
118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy|
113114
119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy|

Diff for: solutions/0114-flatten-binary-tree-to-linked-list.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 114. Flatten Binary Tree to Linked List
3+
* https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, flatten the tree into a "linked list":
7+
* - The "linked list" should use the same TreeNode class where the right child pointer points
8+
* to the next node in the list and the left child pointer is always null.
9+
* - The "linked list" should be in the same order as a pre-order traversal of the binary tree.
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* function TreeNode(val, left, right) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.left = (left===undefined ? null : left)
17+
* this.right = (right===undefined ? null : right)
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @return {void} Do not return anything, modify root in-place instead.
23+
*/
24+
var flatten = function(root) {
25+
if (root === null) return;
26+
27+
if (root.left) {
28+
let previous = root.left;
29+
while (previous.right) {
30+
previous = previous.right;
31+
}
32+
const rightNode = root.right;
33+
root.right = root.left;
34+
previous.right = rightNode;
35+
root.left = null;
36+
}
37+
38+
flatten(root.right);
39+
};

0 commit comments

Comments
 (0)