@maxinimize/

Data Structures: Trees-exercise

JavaScript

No description

fork
loading
main.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
class Node {
  constructor(value){
    this.left = null;
    this.right = null;
    this.value = value;
  }
}

class BinarySearchTree {
  constructor(){
    this.root = null;
  }
  insert(value){
    if (!this.root) {
      this.root = new Node(value)
    } else {
      let currentNode = this.root
      while (true) {
        if (value > currentNode.value) {
          if (!currentNode.right) {
            currentNode.right = new Node(value)
            break;
          }
          currentNode = currentNode.right
        } else {
          if (!currentNode.left) {
            currentNode.left = new Node(value)
            break;
          }
          currentNode = currentNode.left
        }
      }
    }
    // if (!this.root) {
    //   this.root = new Node(value)
    // } else {
    //   let currentNode = this.root
    //   while (currentNode) {
    //     if (value > currentNode.value) {
    //       currentNode = currentNode.right
    //     } else {
    //       currentNode = currentNode.left
    //     } 
    //   }
    //   currentNode = new Node(value)
    // }
  }
  lookup(value){
    let currentNode =this.root
    while (currentNode) {
      if (value > currentNode.value) {
        currentNode = currentNode.right
      } else if (value < currentNode.value) {
        currentNode = currentNode.left
      } else if (value === currentNode.value) {
        return currentNode
      }
    }
    return false
  }
  // remove
}

const tree = new BinarySearchTree();
tree.insert(9)
tree.insert(4)
tree.insert(6)
tree.insert(20)
tree.insert(170)
tree.insert(15)
tree.insert(1)
console.log(tree)
// tree.lookup(90)
// JSON.stringify(traverse(tree.root))

//     9
//  4     20
//1  6  15  170

function traverse(node) {
  const tree = { value: node.value };
  tree.left = node.left === null ? null : traverse(node.left);
  tree.right = node.right === null ? null : traverse(node.right);
  return tree;
}





Native Browser JavaScript