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.