本文主要是介绍二叉树非递归中序遍历(借用stack),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
递归的中序遍历, template < class Entry >
void Binary_tree < Entry > ::recursive_inorder(Binary_node < Entry > * sub_root,
void ( * visit)(Entry ))
{
if (sub_root != NULL) {
recursive_inorder(sub_root->left, visit);
(*visit)(sub_root->data);
recursive_inorder(sub_root->right, visit);
}
}
void Binary_tree < Entry > ::recursive_inorder(Binary_node < Entry > * sub_root,
void ( * visit)(Entry ))
{
if (sub_root != NULL) {
recursive_inorder(sub_root->left, visit);
(*visit)(sub_root->data);
recursive_inorder(sub_root->right, visit);
}
}
根据递归调用函数时栈的情况, 自己手动操作栈,
于是有
#include < stack >
using namespace std;
template < class Entry >
void Binary_tree < Entry > ::NonRecursiveInorder( void ( * visit)(Entry))
{
Binary_node<Entry> *go=root;
stack <Binary_node<Entry>* > stk;
while(!stk.empty() || go!=NULL)
{
if(go!=NULL)
{
stk.push(go);
go=go->left;
}
else
{
go=stk.top();
stk.pop();
(*visit)(go->data);
go=go->right;
}
}
}
using namespace std;
template < class Entry >
void Binary_tree < Entry > ::NonRecursiveInorder( void ( * visit)(Entry))
{
Binary_node<Entry> *go=root;
stack <Binary_node<Entry>* > stk;
while(!stk.empty() || go!=NULL)
{
if(go!=NULL)
{
stk.push(go);
go=go->left;
}
else
{
go=stk.top();
stk.pop();
(*visit)(go->data);
go=go->right;
}
}
}
width="728" scrolling="no" height="90" frameborder="0" align="middle" src="http://download1.csdn.net/down3/20070601/01184120111.htm" marginheight="0" marginwidth="0">
这篇关于二叉树非递归中序遍历(借用stack)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!