Binary Tree search javascript
Now let's talk about searching in Binary Trees. For binary search trees, there are generally three types of searches: maximum value, minimum value, and given value.
The minimum search value is to traverse the left subtree until the last node is found, because the smaller value in the binary search tree is always on the left subnode.
The Code is as follows:
Function getMin () {// find the minimum var current = this. root; // point to the root node while (current. left! = Null) {current = current. left;} return current. data ;}
The code for finding the maximum value is as follows:
Function getMax () {// find the maximum var current = this. root; while (current. right! = Null) {// if the right node is not found, the current = current. right;} return current. data ;}
It is not difficult to find the specified value in the binary search tree, that is, to judge the size of the search value of the node value in sequence. If the node value is small, continue to the right. If the node value is large, the Code is as follows:
Function find (data) {// find a value var current = this. root; while (current! = Null) {if (current. data = data) {return current;} else if (current. data> data) {// If the node value is greater than the search value, find current = current to the left. left;} else {// If the node value is smaller than the search value, find current = current to the right. right ;}}// if not found, return nullreturn null ;}