//原文:
//
// 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 <string>
#include <queue>
#include <stack>
#include <list>
using namespace std;
struct treenode
{
char data;
treenode * left;
treenode * right;
treenode * parent;
};
class tree
{
public:
tree()
{
//root = create();
root = NULL;
index = 0;
}
~tree()
{
/***清空二叉树***/
}
/***二叉排序树:插入。***/
void insert(char *s)
{
if (s == NULL)
{
return;
}
int size = strlen(s);
for (int i = 0; i<size; i++)
{
insert(&root, s[i], NULL);
}
}
void levelOrder()
{
queue<treenode *> q;
if (root != NULL)
{
q.push(root);
}
while(!q.empty())
{
treenode *t = q.front();
cout<<t->data<<endl;
q.pop();
if (t->left != NULL)
{
q.push(t->left);
}
if (t->right != NULL)
{
q.push(t->right);
}
}
}
treenode * findNext(treenode *p)
{
if (p->right == NULL)
{
return p->parent;
}
else
{
treenode *s = p->right;
while(s->left != NULL)
{
s = s->left;
}
return s;
}
}
void preOrder(){ pOrder(root);}
void inOreder(){ zOrder(root);}
void postOreder(){ hOrder(root);}
treenode *root;
private:
int index;
void insert(treenode **p, char s, treenode *parent)
{
if (((*p) == NULL) && s != '\0')
{
*p = new treenode;
(*p)->data = s;
(*p)->left = NULL;
(*p)->right = NULL;
(*p)->parent = parent;
}
else
{
if ((*p)->data > s)
{
insert(&((*p)->left) , s, *p);
}
else
{
insert(&((*p)->right) , s, *p);
}
}
}
void pOrder(treenode *p)
{
if (p==NULL)
{
return;
}
cout<<p->data<<" "<<endl;
pOrder(p->left);
pOrder(p->right);
}
void zOrder(treenode *p)
{
if (p==NULL)
{
return;
}
zOrder(p->left);
cout<<p->data<<" "<<endl;
zOrder(p->right);
}
void hOrder(treenode *p)
{
if (p==NULL)
{
return;
}
hOrder(p->left);
cout<<p->data<<" "<<endl;
hOrder(p->right);
}
};
int main()
{
/**非递归层次遍历*************************/
tree s;
char t[8] = "3289654";
s.insert(t);
//s.levelOrder();
treenode *p =s.findNext((s.root)->right);
cout<<p->data<<endl;
return 0;
}