JavaScript data structures and algorithms-inserting nodes, generating two-fork trees
In a binary tree, a relatively small value is saved on the left node, and a larger value is saved in the right node
/** Binary tree, the relatively small value is saved on the left node, the larger value is saved in the right node * * **//*used to generate a node*/functionNode (data, left, right) { This. data = data;//data stored by the node This. left =Left ; This. right =Right ; This. Show =Show;}functionShow () {return This. Data;}/*used to generate a binary tree*/functionBST () { This. root =NULL; This. Insert =insert;}/*insert data into the binary tree (1) To set the root node as the current node. (2) If the data to be inserted is less than the current node, the new current node is set to the left node of the original node; otherwise, the 4th step is performed. (3) If the left node of the current node is null, the new node is inserted into the position, exiting the loop, and vice versa, continuing with the next loop. (4) Set the new current node to the right node of the original node. (5) If the right node of the current node is null, the new node is inserted into the position, exiting the loop, and vice versa, continuing with the next loop. * */functionInsert (data) {varn =NewNode (data,NULL,NULL); if( This. root = =NULL) { This. root =N; } Else { varCurrent = This. Root; varparent; while(true) {Parent=Current ; if(Data <current.data) { current= Current.left;//if the data to be inserted is less than the current node, the new current node is set to the left node of the original node if(Current = =NULL) {//if the left node of the current node is null, the new node is inserted into the position, exiting the loop, and vice versa, continuing with the next while loop. Parent.left =N; Break; } } Else{ Current= Current.right;//if the data to be inserted is less than the current node, the new current node is set to the left node of the original node if(Current = =NULL) {Parent.right=N; Break; } } } }}varNums =NewBST (); Nums.insert (23); Nums.insert (45); Nums.insert (16); Nums.insert (37); Nums.insert (3); Nums.insert (99); Nums.insert (22); Console.log (nums);
JavaScript data structures and algorithms-two fork tree (insert node, build two fork tree)