Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tree_Preorder_Traversal.js added #2649

Closed
wants to merge 14 commits into from
93 changes: 93 additions & 0 deletions Tree_Preorder_Traversal/Tree_Preorder_Traversal.js.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
//Tree_Preorder_Traversal in javascript
class Node
{
constructor(data)
{
this.data = data;
this.left = null; //left child of the node
this.right = null; //right child of the node
}
}

class BinarySearchTree
{
constructor()
{
this.root = null;
}
//data inserting in tree
insert(data)
{
let node = new Node(data);
if(this.root == null)
{
this.root = node;
}
else
{
this.insertNode(this.root, node);
}
}

insertNode(root, newNode)
{
if(newNode.data < root.data)
{
if(root.left == null)
{
root.left = newNode;
}
else
{
this.insertNode(root.left, newNode);
}
}
else if(newNode.data > root.data)
{
if(root.right == null)
{
root.right = newNode;
}
else
{
this.insertNode(root.right, newNode);
}
}
}

getRootNode()
{
return this.root;
}
//function of preorder traversal
preorder(root)
{
if(root != null)
{
console.log(root.data); // first line - P L R
this.preorder(root.left); // second line
this.preorder(root.right); // third line
}
}
}
var bst = new BinarySearchTree();
//tree data insertion statically
bst.insert(3);
bst.insert(5);
bst.insert(1);
bst.insert(6);
bst.insert(4);
var root = bst.getRootNode();
console.log('Preorder Traversal:');
bst.preorder(root);
console.log('\n');

/*
output:
Preorder Traversal:
3
1
5
4
6
*/