First of all, 22 compare to find the largest element, need n-1 times, that is, the number of non-leaf nodes of the binary tree. Then the largest must be in the element compared with the largest element, a total of lgn-1, that is, the height of the tree. So add up is n+lgn-2
#include <iostream>using namespacestd;classnode{ Public: Node (); Node (intd); Node*Left ; Node*Right ; intdata;}; Node::node () { Right= left =NULL;} Node::node (intd) {Data=D; Right= left =NULL;}classbinarytree{ Public: Node*Root; voidCreate_tree (Node**node,intLen); intMinintAintb); intSearch_second_small (); BinaryTree ();}; Binarytree::binarytree () {root=NewNode ();}intBinarytree::min (intAintb) { returnA < b?a:b;}voidBinarytree::create_tree (Node**node,intLen) { if(Len <2) return; if(len = =2) {root->left = node[0]; Root->right = node[1]; Root->data = min (node[0]->data,node[1]->data); } Else { intNew_len = (len%2) ? (Len/2+1): (Len/2); Node**new_node =Newnode*[New_len]; intMoD = len%2; for(inti =0; i < New_len-mod; i++) {New_node[i]=NewNode (min (node[2*i]->data,node[2(ii1]->data)); New_node[i]->left = node[2*i]; New_node[i]->right = node[2* i +1]; } if(MoD) New_node[new_len-1] = node[len-1]; Create_tree (New_node, New_len); Delete[] new_node; }}intBinarytree::search_second_small () {Node*p =Root; intSecond =0x7fffffff; while(p->left&&p->Right ) { if(P->data = = p->left->data) { if(Second > P->right->data) Second= p->right->data; P= p->Left ; } Else { if(Second > P->left->data) Second= p->left->data; P= p->Right ; } } returnsecond;}intMain () {intArr[] = {1,3,2,4,6,0,9,8}; intN =sizeofARR/sizeofarr[0]; Node**node =Newnode*[N]; for(inti =0; i < N; i++) Node[i]=NewNode (Arr[i]); BinaryTree* Bi_tree =NewBinaryTree (); Bi_tree-create_tree (node, N); cout<< Bi_tree->root->data <<Endl; cout<< Bi_tree->search_second_small () <<Endl; return 0;}
In the worst case, finding the second-small element in n elements requires a n+lgn-2 comparison