Binary Tree search javascript

Source: Internet
Author: User

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 ;}



 



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.