14. For a binary sorting tree, make f = (maximum value + minimum value)/2. design an algorithm to find the node closest to and greater than the value of F.

Source: Internet
Author: User
/*************************************** * Sort binary tree, let f = (maximum value + minimum value)/2, design an algorithm to find the node closest to the F value and greater than the F value. Complexity: O (n2) no score *//********************************** **************************************// /query binary trees, the maximum value is the rightmost node, and the minimum value is the leftmost node // obtain F. Find the value near F binarynode * findf (binarynode * root) {If (! Root) return NULL; int maxval = 0; int minval = 0; // maximum binarynode * pnode = root; while (pnode-> m_right) {pnode = pnode-> m_right ;} maxval = pnode-> m_data; // minimum pnode = root; while (pnode-> m_left) pnode = pnode-> m_left; minval = pnode-> m_data; if (minval = maxval) return NULL; int F = (maxval + minval)/2; pnode = root; // unchanged, the query node must be on the pnode subtree // while (pnode-> m_left | pnode-> m_right) while (1) {If (pnode-> m_data <= f) pnode = pnode-> m_right; If (pnode-> m_data> F) {If (pnode-> m_left & pnode-> m_left-> m_data> F) pnode = pnode-> m_left; elsereturn pnode; }}// return pnode;} void testofquerytree () {const int size = 10; int iarr [size]; initarr (iarr, size); showarr (iarr, size); binarynode * root = buildbinarytree (iarr, 0, size-1); cout <findf (Root)-> m_data <Endl ;}

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.