-
Notifications
You must be signed in to change notification settings - Fork 0
/
144.js
50 lines (45 loc) · 1.17 KB
/
144.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Using Stack
var preorderTraversal = function(root) {
let res=[];
let stk=[];
let curr=root;
while(curr!==null||stk.length>0){
if(curr!==null){
res.push(curr.val);
stk.push(curr);
curr = curr.left;
}else{
curr = stk.pop();
curr = curr.right;
}
}
return res;
};
// Morris traversal
var preorderTraversal = function(root) {
let res=[];
let curr=root;
while(curr!==null){
//if left ltree root === null, move to right root
if(curr.left===null){
res.push(curr.val);
curr = curr.right;
}else{
//find rightmost of left tree
let lroot = curr.left;
let rroot = curr.right;
let rmost = lroot;
while(rmost.right!==null){
rmost = rmost.right;
}
//root-ltree(rmost of ltree)-rtree
curr.right = lroot;
curr.left = null;
rmost.right = rroot;
if(curr.left===null){res.push(curr.val);}
//move to ltree root
curr = lroot;
}
}
return res;
};