/*Write an algorithm to find the ‘next’ node (i e , in-order successor) of a given node in
a binary search tree where each node has a link to its parent
*/
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
class Node{
public:
int data;
Node *lchild,*rchild,*parent;
Node(int a=0, Node*p=0):data(a),parent(p),rchild(0),lchild(0){}
};
class Tree{
public:
Node* root;
Tree():root(0){}
Tree(int ar[],int l){
root = 0;
for(int i = 0; i<l; i++)
insert(ar[i]);
}
void insert(int);
bool is_empty(){ return !root;}
void preorder(Node*);
void successor(Node*);
void destroy(Node*);
};
void Tree::insert(int k){
if(is_empty())
root = new Node(k);
else{
Node* temp = root;
Node* parent;
while(temp){
parent =temp;
if(temp->data > k)
temp = temp->lchild;
else temp = temp->rchild;
}
temp = new Node(k,parent);
if(parent->data>k)
parent->lchild = temp;
else parent->rchild = temp;
}
}
void Tree::preorder(Node* r)
{
if(r){
preorder(r->lchild);
cout<<r->data<<" ";
preorder(r->rchild);
}
}
void Tree::destroy(Node* r){
if(r){
destroy(r->lchild);
destroy(r->rchild);
delete r;
}
}
void Tree::successor(Node*r){
while(r)
{
if(r->rchild){
r = r->rchild;
while(r->lchild)
r = r->lchild;
cout<<r->data<<endl;
}
Node* y = r->parent;
while(y && r == y->rchild){
r = y;
y = y->parent;
}
r = y;
if(r)cout<<r->data<<endl;
}
}
int main(){
int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
Tree ll(ar,16);
ll.preorder(ll.root);
cout<<endl;
ll.successor(ll.root);
ll.destroy(ll.root);
}
careercup4.5
最新推荐文章于 2017-12-01 13:15:00 发布