A data structure that consists of nodes in a parent / child relationship
π©βπ¦
2
12
99
11
2
1
8
9
2
7
44
10
87
55
2
12
11
9
2
2
12
12
11
2
1
8
9
2
7
44
Lists - linear
Trees - nonlinear
(sort of a special case of a tree)
2
12
11
2
12
11
2
12
11
8
9
2
44
2
12
11
8
9
2
44
2
12
12
11
2
1
8
9
2
7
44
Lots of different applications!
1
5
12
11
3
6
1
5
12
11
3
6
9
Lots of different applications as well!
10
6
15
20
8
3
10
8
15
20
6
3
NOPE
10
8
15
20
6
3
NOPE!
4
10
8
15
20
6
3
NOPE!
4
class BinarySearchTree {
constructor(){
this.root = null;
}
}
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
10
6
15
20
8
3
13
10
6
15
20
8
3
13
Steps - Iteratively or Recursively
Steps - Iteratively or Recursively
Insertion - O(log n)
Searching - O(log n)
NOT guaranteed!
Insertion - O(log n)
Searching - O(log n)
NOT guaranteed!
NOT guaranteed!
π¬
π¬
THIS IS A VALID BINARY SEARCH TREE
10
19
6
20
8
99
Two ways:
10
6
15
20
8
3
[10, 6, 15, 3, 8, 20]
Steps - Iteratively
10
6
15
20
8
3
[3, 6, 8, 10, 15, 20]
10
6
15
20
8
3
[3, 6, 8, 10, 15, 20]
Steps - Recursively
10
6
15
20
8
3
[10, 6, 3, 8, 15, 20]
Steps - Recursively
10
6
15
20
8
3
[3, 8, 6, 20, 15, 10]
Steps - Recursively
Which is better?
BREADTH FIRST
Lots of nodes to keep track of!
DEPTH FIRST
Fewer nodes to keep track of
BREADTH FIRST
Fewer nodes to keep track of
10
6
15
20
8
3
[3, 6, 8, 10, 15, 20]
Used commonly with BST's
Notice we get all nodes in the tree in their underlying order
10
6
15
20
8
3
[10, 6, 3, 8, 15, 20]
Can be used to "export" a tree structure so that it is easily reconstructed or copied.
This one can be tough!
10
6
18
20
8
3
15
Steps - Iteratively
10
6
18
20
8
3
10
6
8
3
20
Steps - Iteratively
10
6
18
20
8
3
15
10
6
18
20
8
3
15
6
18
20
8
3
15
Steps - Iteratively