二叉搜索树的插入函数 对照和网上的一模一样 实际运行出了问题 根节点的值运行过程中改变了 。
#include <iostream>
#include <iomanip>
#define NULL 0
using namespace std;
struct Tree_Node
{
int Information;
Tree_Node *Parent;
Tree_Node *Left_Child;
Tree_Node *Right_Child;
Tree_Node(int Informatio);
};
Tree_Node::Tree_Node(int Informatio)
{
Parent=NULL;
Left_Child=NULL;
Right_Child=NULL;
Information=Informatio;
}
class Binary_Search_Tree
{
public:
void Inorder(Tree_Node *Node);
void Preorder();
void Postorder();
void Insert(Tree_Node NewNode);
Binary_Search_Tree();
void See();
public:
Tree_Node *RootNode;
};
void Binary_Search_Tree::See() // 查看RootNode变化情况。
{
cout<<"RootNode:"<<RootNode->Information<<endl;
}
Binary_Search_Tree::Binary_Search_Tree(){RootNode=NULL;}
void Binary_Search_Tree::Insert(Tree_Node NewNode) //
{
if(RootNode!=0){See();} //查看RootNode变化情况
Tree_Node *Trail=NULL;
Tree_Node *Temp=RootNode;
while(Temp!=NULL)
{
Trail=Temp;
if(NewNode.Information<Temp->Information)
{Temp=Temp->Left_Child;}
else{Temp=Temp->Right_Child;}
}
NewNode.Parent=Trail;
if(Trail==NULL){RootNode=&NewNode;}
else
{
if(NewNode.Information<Trail->Information)
{Trail->Left_Child=&NewNode;}
else{Trail->Right_Child=&NewNode;}
}
}
int main()
{
Binary_Search_Tree T;
Tree_Node t1(10);
Tree_Node t2(39);
Tree_Node t3(5);
T.Insert(t1);
T.See();
T.Insert(t2);
return 0;
}
输出结果 RootNode 10
RootNode 39