OneCompiler

SJ9923D9

108
  1. Write a Program for Complete Binary Tree from its Linked List
    Representation?
    <script>

    class ListNode {

        constructor(d) {
this.data = d;
this.next = null;
}
}

class BinaryTreeNode {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}

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

push(new_data) {

var new_node = new ListNode(new_data);

new_node.next = this.head;

this.head = new_node;
}

convertList2Binary(node) {

var q = [];

if (this.head == null) {
node = null;
return null;
}

node = new BinaryTreeNode(this.head.data);
q.push(node);

          this.head = this.head.next;

while (this.head != null) {

var parent = q.shift();

var leftChild = null,
rightChild = null;

leftChild = new BinaryTreeNode(this.head.data);
q.push(leftChild);
this.head = this.head.next;

if (this.head != null) {
rightChild = new BinaryTreeNode(this.head.data);
q.push(rightChild);
this.head = this.head.next;
}

parent.left = leftChild;
parent.right = rightChild;
}

return node;
}
inorderTraversal(node) {
if (node != null) {
this.inorderTraversal(node.left);
document.write(node.data + "");
this.inorderTraversal(node.right);
}
}
}
var tree = new BinaryTree();
tree.push(36);
tree.push(30);
tree.push(25);
tree.push(15);
tree.push(12);

      tree.push(10);
var node = tree.convertList2Binary(tree.root);

document.write(
"Inorder Traversal of the" + " constructed Binary Tree is:<br>");
tree.inorderTraversal(node);

</script>