一、二叉树的先序遍历:首先访问跟节点,再依次访问它的左子树和右子树。
递归方法:
void preorder(node *root)
{
if(NULL == root)
return ;
visit(root);
preorder(root->leftchild);
preorder(root->rightchild);
}
其非递归算法,利用C++STL中的stack(栈)实现。首先分析一个二叉树的前序递归算法的顺序。如下图的二叉树:其前序遍历为ABDCEFGH
其非递归的具体实现代码如下:
void preorder(node *root)
{
if(NULL == root)
return;
stack<node*> node_stack;
node *cur = root;
while(cur!= NULL && !node_stack.empty())
{
while(cur!=NULL)
{
visit(cur);
node_stack.push(cur);
cur = cur->leftchild;
}
if(!node_stack.empty())
{
cur = node_stack.top();
node_stack.pop();
cur = cur ->rightchild;
}
}
}
二、二叉树的中序遍历:首先访问左子树,然后访问根结点,最后访问右子树。
其递归算法如下:
void inorder(node *root)
{
if(NULL = root)
return;
inorder(root->leftchild);
visit(root);l
inorder(root->rightchild);
}
图中二叉树中序遍历的顺序为:BDAFEHGC;
也可以用栈来实现二叉树的中序遍历:
void inorder(node *root)
{
if(root == NULL)
return;
stack<node*> node_stack;
node cur = root;
while(cur != NULL || !node_queue.empty())
{
while(cur != NULL)
{
node_stack.push(cur);
cur = cur->leftchild;
}
if(!node_stack.empty())
{
cur = node_stack.top();
visit(cur);
node_stak.pop();
cur = cur->rightchild;
}
}
}
三、后序遍历:先访问左子树,在访问右子树,最后访问根结点
其递归实现为:
void postorder(node *root)
{
if(NULL == root)
return;
postorder(root->leftchild);
postorder(root->rightchild);
visit(root);
}
对于上图中后序遍历结果为:DBFHGECA
void postorder(node *root)
{
if(NULL == root)
return;
stack<node*> node_stack;
node* cur = root;
node *temp = NULL;
while(cur != NULL || !node_stack.empty())
{
while(cur != NULL)
{
node_stack.push(cur);
cur = cur->leftchild;
}
if(!node_stack.empty())
{
cur = node_stack.top();
if( cur->rightchild == NULL || cur->rightchild == temp)
{
visit(cur);
temp = cur->rightchild;
node_stack.pop();
cur = NULL;
}
else
cur = cur->rightchild;
}
}
}