在一棵空的二叉排序树中依次插入关键字序列为12,7,17,11,16,2,13,9,21,4,试编写程序创建这棵二叉排序树
循环创建每一个节点,并初始化左右孩子为空,利用递归如果下个元素小于当前元素就创建左孩子,否则就创建右孩子输入关键字
结束后就成功创建了一个二叉排序树,左孩子<父<右孩子
#include <iostream>
using namespace std;
#include "BSTree.h"
int main()
{
BSTree T;
CreatBST(T);
PrintBSTree(T);
return 0;
}
#ifndef BSTREE_H_INCLUDED
#define BSTREE_H_INCLUDED
typedef struct {
int key;
char otherinfo;
}ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
void InsertBST(BSTree &T,ElemType e){
BSTree s;
if(!T){
s=new BSTNode;
s->data=e;
s->lchild=s->rchild=NULL;
T=s;
}
else if(e.key<T->data.key)
InsertBST(T->lchild,e);
else if(e.key>T->data.key)
InsertBST(T->rchild,e);
}
void CreatBST(BSTree &T){
ElemType e;
T=NULL;
cin>>e.key;
while(e.key!=1234){ //当输入1234代表输入结束
InsertBST(T,e);
cin>>e.key;
}
}
void PrintBSTree(BSTree T)
{
if(T)
{
PrintBSTree(T->lchild);
cout<<T->data.key<<" "<<endl;
PrintBSTree(T->rchild);
}
}
#endif // BSTREE_H_INCLUDED
构建二叉排序树的示例代码
这篇博客展示了如何通过C++代码创建一个二叉排序树。文章以插入关键字序列12, 7, 17, 11, 16, 2, 13, 9, 21, 4为例,详细解释了如何利用递归方法在空树中插入节点,确保树保持左孩子小于父节点、父节点小于右孩子的特性。"
106387587,9427317,最长公共子序列算法详解,"['算法', '动态规划', '字符串处理', '递归']

被折叠的 条评论
为什么被折叠?



