温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

二叉树的非递归遍历

发布时间:2020-07-17 22:20:13 来源:网络 阅读:378 作者:羌笛夜 栏目:编程语言
template<class T>
void BinaryTree<T>:: PrevOrderNoRec()
{
	if (_root == NULL)
	{
		return;
	}
	stack<Node*> s;
	s.push(_root);

	while (!s.empty())
	{
		Node* top = s.top();//获取栈顶
		cout << top->_data << " ";
		s.pop();

		//右孩子入栈
		if (top->_rightChild)
		{
			s.push(top->_rightChild);
		}
		
		//左孩子入栈
		if (top->_leftChild)
		{
			s.push(top->_leftChild);
		}
	}
	cout << endl;
}


template<class T>
void BinaryTree<T>::InOrderNoRec()
{
	if (_root == NULL)
	{
		return;
	}
	Node* cur = _root;
	stack<Node*> s;
	while (cur||!s.empty())//如果栈为空并且cur==NULL跳出循环
	{
		//找到最左下方的节点访问
		while (cur)
		{
			s.push(cur);
			cur = cur->_leftChild;
		}
		
		Node* top = s.top();
		cout << top->_data << " ";
		s.pop();

		//如果右子树不为空则按照中序遍历,重新找到最左下角的继续访问
		if (top->_rightChild)
		{
			cur = top->_rightChild;
		}

		//如果右子树为空,则cur==NULL,不会再次进入循环,直接出栈访问
	}
	cout << endl;
}


template<class T>
void BinaryTree<T>::PosOrderNoRec()
{
	if (_root == NULL)
	{
		return;
	}

	Node* cur = _root;//当前指针
	Node* prev = NULL;//栈内的前驱指针
	stack<Node*> s;
	while (cur || !s.empty())
	{
		//找到最左下角节点
		while (cur)
		{
			s.push(cur);
			cur = cur->_leftChild;
		}

		Node* top = s.top();
		
		//如果右子树为空,或者之前访问过则输出
		if (top->_rightChild == NULL || prev == top->_rightChild)
		{
			cout << top->_data << " ";
			prev = top;//出栈之前更新prev
			s.pop();
		}
		else
		{
			cur = top->_rightChild;
		}
	}
	cout << endl;
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI