二叉搜索树的第K个接点,
其中包含了二叉搜索树的创建,寻找其后继;
最小节点等,,若干关于二叉搜索树的操作
#include<iostream>
#include<queue>
using namespace std;
struct Node{
int data;
Node *left;
Node *right;
Node *parent;
Node(int value):data(value),left(NULL),right(NULL),parent(NULL){}
};
class tree{
private:
Node *root;
public:
tree():root(NULL){}
void insert(Node *node)
{
if(root==NULL)
{
root=node;
return ;
}
Node *y=NULL;
Node *x=root;
while(x!=NULL)
{
y=x;
if(node->data<x->data)
{
x=x->left;
}
else
{
x=x->right;
}
}
node->parent=y;
if(node->data<y->data)
{
y->left=node;
}
else
{
y->right=node;
}
}
void inorder_traverse(Node *node)
{
if(node==NULL)
{
return ;
}
inorder_traverse(node->left);
cout<<node->data<<" ";
inorder_traverse(node->right);
}
Node *get_root()
{
return root;
}
Node *tree_minimum(Node *head)
{
Node* node=head;
if(NULL==node)
{
return NULL;
}
while(node->left!=NULL)
{
node=node->left;
}
return node;
}
Node *successor(Node *new_node)
{
Node *node=root;
if(new_node==NULL)
{
cout<<"空树,它是没有后继接点的"<<endl;
return NULL;
}
if(new_node->right!=NULL)
{
return tree_minimum(new_node->right);
}
else
{
Node *y=NULL,*cur_node=new_node;
y=new_node->parent;
if(y==NULL)
{
cout<<"没有后继接点"<<endl;
return NULL;
}
else
{
while(y!=NULL&&cur_node==y->right)
{
}
}
}
}
};
void print(Node *root)
{
if(root==NULL)
{
cout<<"此数是空的"<<endl;
return ;
}
int to_delete=1;
int next_num=0;
queue<Node *> nodes;
nodes.push(root);
while(!nodes.empty())
{
Node *node=nodes.front();
cout<<node->data<<"\t";
if(node->left!=NULL)
{
nodes.push(node->left);
++next_num;
}
if(node->right!=NULL)
{
nodes.push(node->right);
++next_num;
}
nodes.pop();
to_delete--;
if(to_delete==0)
{
cout<<endl;
to_delete=next_num;
next_num=0;
}
}
}
Node *Kth_node_core(Node *root,int &k)
{
Node *target=NULL;
if(root->left!=NULL)
{
target=Kth_node_core(root->left,k);
}
if(target==NULL)
{
if(k==1)
target=root;
k--;
}
if(target==NULL&&root->right!=NULL)
{
target=Kth_node_core(root->right,k);
}
return target;
}
Node *Kth_node(Node *root,int k)
{
if(root==NULL||k<=0)
return NULL;
return Kth_node_core(root,k);
}
int main()
{
Node *node1=new Node(8);
Node *node2=new Node(6);
Node *node3=new Node(5);
Node *node4=new Node(7);
Node *node5=new Node(11);
Node *node6=new Node(10);
Node *node7=new Node(12);
tree *b_tree=new tree();
b_tree->insert(node1);
b_tree->insert(node2);
b_tree->insert(node3);
b_tree->insert(node4);
b_tree->insert(node5);
b_tree->insert(node6);
b_tree->insert(node7);
//print(b_tree->get_root());
int k=3;
Node *result=Kth_node(b_tree->get_root(),k);
cout<<result->data<<endl;
cout<<endl;
system("pause");
return 0;
}