Movatterモバイル変換


[0]ホーム

URL:


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

Commitff610c9

Browse files
another recursive solution
1 parent3121d3d commitff610c9

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

‎114 Flatten Binary Tree to Linked List.js

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,44 @@
1616
varflatten=function(root){
1717
varstack=[];
1818
varp=root;
19-
19+
2020
while(p!==null||stack.length!==0){
2121
if(p.right!==null){
2222
stack.push(p.right);
2323
}
24-
24+
2525
if(p.left!==null){// [!!!]point of confusing, if null then pop stack
2626
p.right=p.left;
2727
p.left=null;
2828
}elseif(stack.length!==0){
2929
varnode=stack.pop();
3030
p.right=node;
3131
}
32-
32+
3333
p=p.right;
3434
}
3535
};
3636

37+
// Recursive solution
38+
39+
varflatten=function(root){
40+
if(root===null||(root.left===null&&root.right===null)){
41+
return;
42+
}
43+
44+
varrootLeft=root.left;
45+
varrootRight=root.right;
46+
root.left=null;
47+
root.right=null;
48+
49+
flatten(rootLeft);
50+
flatten(rootRight);
51+
52+
root.right=rootLeft;
53+
54+
varaux=root;
55+
while(aux!==null&&aux.right!==null){
56+
aux=aux.right;
57+
}
58+
aux.right=rootRight;
59+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp