-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinOrder.js
More file actions
88 lines (70 loc) · 1.73 KB
/
inOrder.js
File metadata and controls
88 lines (70 loc) · 1.73 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* https://leetcode.com/problems/binary-tree-inorder-traversal/#/description */
var createMinBst = require('./BST').createMinBST;
var tree = createMinBst([1,2,3,4,5,6,7,8]);
// console.log(inOrder(tree));
// console.log(itrInOrder(tree));
console.log(morris(tree));
function inOrder(root) {
var res = [];
function helper(root) {
if (root === null){
return;
}
if(root.left !== null) {
helper(root.left);
}
res.push(root.val);
if(root.right !== null) {
helper(root.right);
}
}
helper(root);
return res;
}
function itrInOrder(root) {
var stack = [];
var res = [];
if(root === null){
return res;
}
stack.push(root);
var current = root.left;
while(current !== null){
stack.push(current);
current = current.left;
}
while(stack.length > 0){
var node = stack.pop();
res.push(node.val);
current = node.right;
while(current !== null){
stack.push(current);
current = current.left;
}
}
return res;
};
function morris(root){
debugger;
var res = [];
while(root) {
if(root.left){
var left = root.left;
while(left.right && left.right !== root) {
left = left.right;
}
if(left.right){
left.right = null;
res.push(root.val);
root = root.right;
} else {
left.right = root;
root = root.left;
}
} else {
res.push(root.val);
root = root.right;
}
}
return res;
}