递归实现二叉树(插入、搜索)
// Binary Search Tree - Implemenation in C++
// Simple program to create a BST of integers and search an element in it
#include<iostream>
using namespace std;
//Definition of Node for Binary search tree
struct BstNode {
int data;
BstNode* left;
BstNode* right;
};
// Function to create a new Node in heap
BstNode* GetNewNode(int data) {
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// To insert data in BST, returns address of root node
BstNode* Insert(BstNode* root,int data) {
if(root == NULL) { // empty tree
root = GetNewNode(data);
}
// if data to be inserted is lesser, insert in left subtree.
else if(data <= root->data) {
root->left = Insert(root->left,data);
}
// else, insert in right subtree.
else {
root->right = Insert(root->right,data);
}
return root;
}
//To search an element in BST, returns true if element is found
bool Search(BstNode* root,int data) {
if(root == NULL) {
return false;
}
else if(root->data == data) {
return true;
}
else if(data <= root->data) {
return Search(root->left,data);
}
else {
return Search(root->right,data);
}
}
int main() {
BstNode* root = NULL; // Creating an empty tree
/*Code to test the logic*/
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,25);
root = Insert(root,8);
root = Insert(root,12);
// Ask user to enter a number.
int number;
cout<<\"Enter number be searched\\n\";
cin>>number;
//If number is found, print \"FOUND\"
if(Search(root,number) == true) cout<<\"Found\\n\";
else cout<<\"Not Found\\n\";
}
编程中最没用的东西是源代码,最有用的东西是算法和数据结构。
继续阅读与本文标签相同的文章
-
日本丰田和美国通用等8家企业联合开发自动驾驶技术
2026-05-18栏目: 教程
-
发布K12教育机械臂,越疆完成全龄段AI教育布局
2026-05-18栏目: 教程
-
有人试图用AI解读《未命名的鹅戏》里的鹅
2026-05-18栏目: 教程
-
MongoDB副本集
2026-05-18栏目: 教程
-
泉州市加快实施“互联网 生产基地 物流”着力构建区域物流枢纽新格局
2026-05-18栏目: 教程
