-
Notifications
You must be signed in to change notification settings - Fork 0
/
traversing-trees.js
60 lines (52 loc) · 1.24 KB
/
traversing-trees.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
class BinaryTreeNode {
constructor(value, left, right) {
Object.assign(this, { value, left, right })
}
}
let root = new BinaryTreeNode(
4,
new BinaryTreeNode(6, new BinaryTreeNode(2), new BinaryTreeNode(1)),
new BinaryTreeNode(3)
)
let inOrder = (root) => {
let results = ''
traverse(root)
return results
function traverse(root) {
if (!root) {
return
}
root.left && traverse(root.left)
results += `${root.value} `
root.right && traverse(root.right)
}
}
console.log(inOrder(root))
let preOrder = (root) => {
let results = ''
traverse(root)
return results
function traverse(root) {
if (!root) {
return
}
results += `${root.value} `
root.left && traverse(root.left)
root.right && traverse(root.right)
}
}
console.log(preOrder(root))
let postOrder = (root) => {
let results = ''
traversePostOrder(root)
return results
function traversePostOrder(root) {
if (!root) {
return
}
root.left && traversePostOrder(root.left)
root.right && traversePostOrder(root.right)
results += `${root.value} `
}
}
console.log(postOrder(root))