267-二叉排序树中序遍历(非递归不用栈队列)

对二叉排序树中序遍历(非递归不用栈队列)

在这里插入图片描述
找到这棵树的中序遍历的第一个节点
相当于找这课二叉树的最小值

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林林林ZEYU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值