-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinaryTree.js
137 lines (104 loc) · 1.97 KB
/
BinaryTree.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
'use strict'
/* BinaryTree
*
* root
* / \
* left right
*
*
*/
const Queue = require("./LinkedQueue");
function BinaryTreeNode(value){
this.val = value;
this.right = this.left = null;
}
module.exports = class BinaryTree{
constructor(){
this._root = null;
}
static Node(value){
return new BinaryTreeNode(value);
}
*inOrder(){
yield* _inOrder(this._root);
}
*preOrder(){
yield* _preOrder(this._root);
}
*postOrder(){
yield* _postOrder(this._root);
}
*levelOrder(){
if(!this._root){
return;
}
let queue = new Queue(), node = null;
queue.enqueue(this._root);
while( queue.length ){
node = queue.dequeue();
if(node.left)
queue.enqueue(node.left);
if(node.right)
queue.enqueue(node.right);
yield node.val;
}
}
/* The number of edges from the root to the node
* val - the value of the node
*/
depth(val){
if(undefined === val || null === val){
return 0;
}
let queue = new Queue(), e = null;
queue.enqueue({depth:0, node: this._root});
while( queue.length ){
e = queue.dequeue();
if(val === e.node.val){
return e.depth;
}
if(e.node.left)
queue.enqueue({node: e.node.left, depth:e.depth + 1});
if(e.node.right)
queue.enqueue({node: e.node.right, depth:e.depth + 1});
}
}
/*
* [node] - is the root.val by default
*/
height(){
}
toArray(){
return [..._inOrder(this._root)];
}
clear(){
this._root = null;
}
get root(){
return this._root;
}
set root(value){
this._root = value;
}
}
function *_inOrder(node){
if(null === node)
return;
yield* _inOrder(node.left);
yield node.val;
yield* _inOrder(node.right);
}
function *_preOrder(node){
if(null === node)
return;
yield node.val;
yield* _preOrder(node.left);
yield* _preOrder(node.right);
}
function *_postOrder(node){
if(null === node)
return;
yield* _postOrder(node.left);
yield* _postOrder(node.right);
yield node.val;
}