Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Last active February 5, 2023 09:11
Show Gist options
  • Save jordanrios94/8c73108114adc0f67eb58ee32c409d1a to your computer and use it in GitHub Desktop.
Save jordanrios94/8c73108114adc0f67eb58ee32c409d1a to your computer and use it in GitHub Desktop.
/*
- Implement the Node class to create a binary search tree. The constructor should initialize values 'data', 'left', and 'right'.
- Implement the 'insert' method for the Node class. Insert should accept an argument 'data', then create an insert a new node at the appropriate location in the tree.
- Implement the 'contains' method for the Node class. Contains should accept a 'data' argument and return the Node in the tree with the same value.
*/
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
insert(data) {
if (data < this.data && this.left) {
this.left.insert(data);
} else if (data < this.data) {
this.left = new Node(data);
} else if (data > this.data && this.right) {
this.right.insert(data);
} else if (data > this.data) {
this.right = new Node(data);
}
}
contains(data) {
if (this.data === data) {
return this;
}
if (this.data < data && this.right) {
return this.right.contains(data);
} else if (this.data > data && this.left) {
return this.left.contains(data);
}
return null;
}
}
@jordanrios94
Copy link
Author

corrected my original contains method

 contains(data) {
    if (this.data == data) {
      return this;
    } else if (this.left && this.left.data === data) {
      return this.left;
    } else if (this.right && this.right.data === data) {
      return this.right;
    } else if (data < this.data && this.left) {
      return this.left.contains(data);
    } else if (data > this.data && this.right) {
      return this.right.contains(data);
    }
    
    return null;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment