Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a2ee318

Browse files
114. Flatten Binary Tree to Linked List
1 parent 4b9bc8a commit a2ee318

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
2+
/**
3+
* 114. Flatten Binary Tree to Linked List
4+
* Definition for a binary tree node.
5+
* function TreeNode(val, left, right) {
6+
* this.val = (val===undefined ? 0 : val)
7+
* this.left = (left===undefined ? null : left)
8+
* this.right = (right===undefined ? null : right)
9+
* }
10+
*/
11+
/**
12+
* @param {TreeNode} root
13+
* @return {void} Do not return anything, modify root in-place instead.
14+
*/
15+
var flatten = function (root) {
16+
while (root) {
17+
if (!root.left) {
18+
root = root.right;
19+
continue;
20+
}
21+
let pre = root.left;
22+
while (pre.right) {
23+
pre = pre.right;
24+
}
25+
pre.right = root.right;
26+
root.right = root.left;
27+
root.left = null;
28+
root = root.right;
29+
}
30+
};
31+
32+
var flatten = function (root) {
33+
if (!root) {
34+
return root;
35+
}
36+
const stack = [];
37+
38+
while (root.left || root.right || stack.length) {
39+
if (root.right) {
40+
stack.push(root.right);
41+
}
42+
if (root.left) {
43+
root.right = root.left;
44+
root.left = null;
45+
} else {
46+
root.right = stack.pop();
47+
}
48+
root = root.right;
49+
}
50+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /