Check if a number is in the binary tree, if it exists, return true

#include<iostream>
#include<vector>
using namespace std;
//same as linked list data structure
struct TreeNode{
  
    int value;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):value(x),left(NULL),right(NULL){}
};

bool  BST_search(TreeNode* node, int val){

    if(node->value  == val){
        return true;
    }
    if(node->value > val){
 
        if(node->left == NULL){
           return false;
        }else{
           BST_search(node->left, val);
        }
    }else{

        if(node->right == NULL){
            return false;
        }else{
            BST_search(node->right, val);
        }
    }

}


int main(){
    TreeNode a(8);
    TreeNode b(3);
    TreeNode c(10);
    TreeNode d(1);
    TreeNode e(6);
    TreeNode f(15);
    a.left =&b;
    a.right = &c;
    b.left = &d;
    b.right = &e;
    c.right = &f;
   
    for(int i = 0; i< 18; i++){
        if(BST_search(&a, i)){
            cout<<i<<"is in the BST"<<endl;
        }else{
            cout<<i<<"is not in the BST"<<endl;
        }
    
    }
      
    return 0;
}
The creation of a binary tree can also be created in a manner similar to a linked list, but the link relationship of the nodes is different

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326590612&siteId=291194637