1
2 class Node {
3 constructor(value){
4 this.left = null;
5 this.right = null;
6 this.value = value;
7 }
8 }
9
10 class BinarySearchTree {
11 constructor(){
12 this.root = null;
13 }
14 insert(value){
15 const newNode = new Node(value);
16 if (this.root === null) {
17 this.root = newNode;
18 } else {
19 let currentNode = this.root;
20 while(true){
21 if(value < currentNode.value){
22 //Left
23 if(!currentNode.left){
24 currentNode.left = newNode;
25 return this;
26 }
27 currentNode = currentNode.left;
28 } else {
29 //Right
30 if(!currentNode.right){
31 currentNode.right = newNode;
32 return this;
33 }
34 currentNode = currentNode.right;
35 }
36 }
37 }
38 }
39 }
40
41 const tree = new BinarySearchTree();
42 tree.insert(9)
43 tree.insert(4)
44 tree.insert(6)
45 tree.insert(20)
46 tree.insert(170)
47 tree.insert(15)
48 tree.insert(1)
49 JSON.stringify(traverse(tree.root))
50
51 // 9
52 // 4 20
53 //1 6 15 170
54
55 function traverse(node) {
56 const tree = { value: node.value };
57 tree.left=node.left
58 if(node.left===null) {
59 return null
60 }else{
61 traverse(node.left);
62 }
63 tree.right=node.right
64 if(node.right===null) {
65 return null
66 }else{
67 traverse(node.right);
68 }
69 }