Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Should I put `addNode()` in the `Node` class or `Tree`?

I'm trying to implement a binary search tree (BST) with javascript. I came up with 2 versions.

Here is the first version

class Node {
  constructor(value) {
    this.value = value
    this.left = null
    this.right = null
  }
}

class Tree {
  constructor(value) {
    if (value != null) {
      this.root = new Node(value)
    } else {
      return null;
    }
  }
  addNode(parent, n) {
    if (n.value === parent.value) {
      return;
    } else if (n.value < parent.value) {
      if (parent.left == null) {
        parent.left = n;
      } else {
        this.addNode(parent.left, n)
      }
    } else { // n.value > parent.value
      if (parent.right == null) {
        parent.right = n;
      } else {
        this.addNode(parent.right, n)
      }
    }
  }
  addValue(val) {
    let n = new Node(val);
    if (this.root == null) {
      this.root = n;
    } else {
      this.addNode(this.root, n);
    }
  }
}

I defined a simple class Node and the Tree class.

The Node class abstracts any node that ranges from the root to a leaf.

The Tree class handles all the business, especially the addNode method. In contrast, my 2nd version put the addNode method in Node class. Here is the code

class Node {
  constructor(value) {
    this.value = value
    this.left = null
    this.right = null
  }
  addNode(n) {
    if (n.value == this.value) {
      return;
    } else if (n.value < this.value) {
      if (this.left == null) {
        this.left = n;
      } else {
        this.left.addNode(n)
      }
    } else {
      if (this.right == null) {
        this.right = n;
      } else {
        this.right.addNode(n)
      }
    }
  }
}

class Tree {
  constructor(value) {
    if (value != null) {
      this.root = new Node(value)
    } else {
      return null;
    }
  }
  addValue(val) {
    let n = new Node(val);
    if (this.root == null) {
      this.root = n;
    } else {
      this.root.addNode(n);
    }
  }
}

Both versions works as expected. I know I should add more check, in case something like tree.addValue(); happens.

I'd just like to know which version should I go with, and why. Are there some kind of principles or consideration to make such decision?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!