-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_223.js
68 lines (60 loc) Β· 1.38 KB
/
problem_223.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
/**
* TreeNode Constructor
* @param {(number | string)} val
*/
function TreeNode(val) {
this.val = val;
this.left = null;
this.right = null;
}
/**
* Computes in order traversal
* Time Complexity: O(n)
* Space Complexity: O(1)
* n - number of nodes
* @param {TreeNode} root
*/
function morrisTraversal(root) {
let current = root;
let inOrder = ``;
while (current !== null) {
// check left node
if (current.left === null) {
inOrder += `${current.val} `;
current = current.right;
} else {
// Find the predecessor of current
let pre = current.left;
while (pre.right !== null && pre.right !== current) pre = pre.right;
// Make current as right child of its in-order predecessor
if (pre.right === null) {
pre.right = current;
current = current.left;
} else {
// Revert the changes (fix right predecssor)
pre.right = null;
inOrder += `${current.val} `;
current = current.right;
}
}
}
return inOrder;
}
const a = new TreeNode(1);
const b = new TreeNode(2);
const c = new TreeNode(3);
const d = new TreeNode(4);
const e = new TreeNode(5);
a.left = b;
a.right = c;
b.left = d;
b.right = e;
/*
Constructed binary tree:
1
/ \
2 3
/ \
4 5
*/
console.log(morrisTraversal(a)); // 4 -> 2 -> 5 -> 1 -> 3