File tree 1 file changed +12
-11
lines changed
scripts/algorithms/F/Flatten Binary Tree to Linked List
1 file changed +12
-11
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 134 ms (Top 14.04%) | Memory: 45 MB (Top 18.98%)
1
2
/**
2
3
* Definition for a binary tree node.
3
4
* function TreeNode(val, left, right) {
4
- * this.val = (val===undefined ? 0 : val)
5
- * this.left = (left===undefined ? null : left)
6
- * this.right = (right===undefined ? null : right)
5
+ * this.val = (val===undefined ? 0 : val)
6
+ * this.left = (left===undefined ? null : left)
7
+ * this.right = (right===undefined ? null : right)
7
8
* }
8
9
*/
9
10
/**
13
14
var flatten = function ( root ) {
14
15
const dfs = ( node ) => {
15
16
if ( ! node ) return
16
-
17
+
17
18
if ( ! node . left && ! node . right ) return node
18
-
19
+
19
20
const leftNode = node . left
20
21
const rightNode = node . right
21
-
22
+
22
23
const leftTree = dfs ( leftNode )
23
24
const rightTree = dfs ( rightNode )
24
-
25
+
25
26
if ( leftTree ) leftTree . right = rightNode
26
-
27
+
27
28
node . left = null
28
29
node . right = leftNode || rightNode
29
-
30
+
30
31
return rightTree || leftTree
31
32
}
32
-
33
+
33
34
dfs ( root )
34
35
return root
35
- } ;
36
+ } ;
You can’t perform that action at this time.
0 commit comments