对二叉排序树中序遍历(非递归不用栈队列)
找到这棵树的中序遍历的第一个节点
相当于找这课二叉树的最小值
BstNode* First(BstNode* ptr)//找到这棵树的中序遍历的第一个节点
{
while (ptr != nullptr && ptr->leftchild != nullptr)
{
ptr = ptr->leftchild;
}
return ptr;
}
找到这棵树的中序遍历的最后一个节点
相当于找这棵二叉树的最大值
BstNode* Last(BstNode* ptr)//找到这棵树的中序遍历的最后一个节点
{
while (ptr != nullptr && ptr->rightchild != nullptr)
{
ptr = ptr->rightchild;
}
return ptr;
}
非递归不用栈队列的中序遍历
void NiceInOrder(BstNode* ptr)
{
for (BstNode* p = First(ptr); p != nullptr; p = Next(p))
{
cout << p->key << " ";
}
cout << endl;
}
如何书写Next函数(中序遍历的后继)?
迭代器方案
我们的9是17的左孩子,23是45的左孩子,45和17之间是右孩子关系,把45给17,17给给根节点。
最开始的时候ptr指向09结点,pa指向17
然后pa=ptr
BstNode* Next(BstNode* ptr)//寻找中序遍历的后继
{
if (ptr == nullptr) return nullptr;
if (ptr->rightchild != nullptr)
{
return First(ptr->rightchild);
}
else
{
BstNode* pa = ptr->parent;
while (pa != nullptr && pa->leftchild != ptr)
{
ptr = pa;
pa = ptr->parent;
}
return pa;
}
}
逆向迭代方案
void ResNiceInOrder(BstNode* ptr)
{
for (BstNode* p = Last(ptr); p != nullptr; p = Prev(p))
{
cout << p->key << " ";
}
cout << endl;
}
如何书写Prev函数(中序遍历的前驱)?
BstNode* Prev(BstNode* ptr)
{
if (ptr == nullptr) return nullptr;
if (ptr->leftchild != nullptr)
{
return Last(ptr->leftchild);
}
else
{
BstNode* pa = ptr->parent;
while (pa != nullptr && pa->rightchild != ptr)
{
ptr = pa;
pa = ptr->parent;
}
return pa;
}
}
在没有双亲的二叉排序树中用中序遍历
实际上就是把二叉树改装为中序遍历的二叉链表
把左孩子当做前驱看待,把右孩子当做后继来看待
9的前驱变为空,9的后继指向17。17的前驱指向9,17的后继指向23,23 的前驱指向17,23的后继指向45。
就地转化成双链表,不存在插入和删除操作
BstNode * InOrderList(BstNode* ptr)//中序的二叉链表
{
if (ptr == nullptr) return nullptr;
stack<BstNode*> st;
BstNode* newroot = nullptr;//根要发生改变
BstNode* pre = nullptr;//定义前驱
while (ptr != nullptr || !st.empty())
{
while (ptr != nullptr)
{
st.push(ptr);
ptr = ptr->leftchild;
}
ptr = st.top(); st.pop();
if (pre == nullptr)//中序遍历的是第一个结点
{
newroot = ptr;
pre = ptr;
}
else
{
pre->rightchild = ptr;
ptr->leftchild = pre;
pre = ptr;
}
ptr = ptr->rightchild;
}
return newroot;
}
插入函数
bool Insert(BstNode*& ptr, KeyType kx)
{
if (ptr == nullptr)
{
ptr = Buynode(kx);
return true;
}
BstNode* pa = nullptr;
BstNode* p = ptr;
while (p != nullptr && p->key != kx)
{
pa = p;
p = kx < p->key ? p->leftchild : p->rightchild;
}
if (p != nullptr && p->key == kx) return false;
p = Buynode(kx);
if (p->key < pa->key)
{
pa->leftchild = p;
}
else
{
pa->rightchild = p;
}
return true;
}