0

I'm trying to invert a binary tree in javascript, but i can't figure out why I'm not getting it to print my tree. It seems like i can create my tree in the example code in the bottom, but i cant get it to save the data.

// A node contains the value, left and right pointers
class Node {
  constructor(item) {
    this.data = item;
    this.left = this.right = null;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  invert() {
    this.root = this.invert(this.root);
  }

  invert(node) {
    if (node == null)
      return node;

    /* recursive calls */
    let left = this.invert(node.left);
    let right = this.invert(node.right);

    /* swap the left and right pointers */
    node.left = right;
    node.right = left;

    return node;
  }

  printTree() {
    this.printTree(this.root);
  }

  // print InOrder binary tree traversal.	
  printTree(node) {
    if (node == null)
      return;

    this.printTree(node.left);
    console.log(node.data + " ");
    this.printTree(node.right);
  }
}

/* testing for example nodes */
const tree = new BinaryTree();
tree.root = new Node(2);
tree.root.left = new Node(11);
tree.root.right = new Node(4);
tree.root.right.left = new Node(13);
tree.root.right.right = new Node(5);

/* log inorder traversal of the input tree */
console.log("Inorder traversal of input tree is :");
tree.printTree();
console.log("");

/* invert tree */
tree.invert();

/* log inorder traversal of the minor tree */
console.log("Inorder traversal of binary tree is : ");
tree.printTree();

What am i doing wrong here to not get it to print the tree, and then invert it.

1

1 Answer 1

1

You can't overload functions in javascript, it will always call the same function regardless of which one "matches".

class Demo {
    overload(a) {
        console.log('hi');
    }
    overload() {
        console.log('bye');
    }
    overload(a, b) {
        console.log('wow');
    }
}

const d = new Demo();
d.overload();
d.overload(1);
d.overload(1, 2);

Because you start with tree.printTree();, and it's actually calling:

printTree(node) {
  if (node == null)
    return;

  this.printTree(node.left);
  console.log(node.data + " ");
  this.printTree(node.right);
}

AND you used == instead of ===, you are essentially calling:

printTree() {
    if (true) {
        return;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.