-
Notifications
You must be signed in to change notification settings - Fork 0
/
binaryTreeTraversals.js
77 lines (72 loc) · 1.8 KB
/
binaryTreeTraversals.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
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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
// Morris
var inorderTraversal = function(root) {
let current = root, inorderArr = [];
while(current != null){
if(current.left != null) {
let newPtr = current.left;
while(newPtr.right != null && newPtr.right != current){
newPtr = newPtr.right;
}
if(newPtr.right == null) {
newPtr.right = current;
current = current.left;
} else {
newPtr.right = null;
inorderArr.push(current.val);
current = current.right;
}
} else {
inorderArr.push(current.val);
current = current.right;
}
}
return inorderArr;
}
/**
// Iterative
function pushAllLeft(current, stack) {
while(current != null){
stack.push(current);
current = current.left;
}
}
var inorderTraversal = function(root) {
let inorderArr = [];
let current = root, stack = [];
pushAllLeft(current, stack);
while(stack.length){
current = stack.pop();
inorderArr.push(current.val);
pushAllLeft(current.right, stack);
}
return inorderArr;
};
*/
/**
// Recursive
function inOrder(pointer, arr) {
if(!pointer) return;
else {
inOrder(pointer.left, arr);
arr.push(pointer.val);
inOrder(pointer.right, arr);
}
}
var inorderTraversal = function(root) {
let arr = [];
inOrder(root, arr);
return arr;
};
*/