JavaScript defines how to write the code for a binary search tree.
Today, the editor will share with you the relevant knowledge points about how to write the code of the JavaScript definition binary search tree. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
The binary search tree consists of nodes, so we define a Node object with the following code:
Function Node (data,left,right) {/ / Node class this.data=data; this.left=left; this.right=right; this.show=show;} function show () {/ / display the data in the node return this.data;}
Left and right are used to point to the left and right child nodes, respectively.
Next, you need to create the class of the binary lookup tree, as follows:
Function BST () {/ / tree class this.root=null; this.insert=insert; this.inOrder=inOrder; this.preOrder=preOrder; this.postOrder=postOrder;}
Next is the code to insert the node. Go through the small ones on the left and the big ones on the right. The code is as follows:
Function insert (data) {/ / insert operation var n=new Node (data,null,null); if (this.root==null) {/ / first element this.root=n;} else {var current=this.root;// always points to the root node var parent; while (true) {/ / until the left or right node is found parent=current; if (data