Knowledge:
#include <iostream> using namespace std; int flag; typedef struct node { int data; struct node * lchild, * rchild ; } Tree; void CreateHead (Tree * & root) { root = new Tree; cin >> root-> data; the root -> = lchild directory root-> rchild = NULL; } // input value root void CreateTree (the root tree * &, int K) // K data elements // create a binary sort tree { IF(the root == NULL) // When the root node is empty { the root = new new Tree; directory root-> Data = K; the root -> = lchild directory root-> rchild = NULL; return ; } the else IF (directory root-> Data > k) // The input data element is smaller than the root node { CreateTree (root-> lchild, k); // Store to the left subtree } else if (root-> data <k) // The input data element is more than root Large node { CreateTree (root- > rchild, k); // Store to the right subtree } } void Searchkey (Tree * root, int key, int count) // key means the element to be found, count means count { if (root == NULL) // when the node is empty, return { return ; } if (key = = root-> data) // When the value of the root node is equal to the value to be found { cout << count; flag = 1 ; return ; // If it is found, the output count times // The flag is assigned a value of 1 } else if (key < root-> data) // When the key is less than the root node, go to the left subtree { Searchkey ( root-> lchild , key, count + 1 ); } else if (key> root-> data) // When the key is greater than the root node, go to the right subtree { Searchkey ( root-> rchild , key, count + 1 ); } } int main () { int n; cin >> n; // Number of elements int i; int count = 1 ; Tree * root; CreateHead (root); int k; for (i = 2 ; i < = n; i ++)// Because an element has been entered in CreateHead { cin >> k; CreateTree (root, k); } // Create a binary sorting tree flag = 0 ; // Initialize to 0 int key; cin >> key; Searchkey ( root, key, count); if (flag == 0 ) cout << " -1 " ; return 0 ; }