二叉树的中序遍历

如下图表示一颗二叉树,对它进行先序遍历操作,采用两种方法,递归和非递归操作。。

遍历结果为:4251637。。

1、递归操作:

思想:若二叉树为空,返回。否则

1)中序遍历左子树;2)访问根节点;3)中序遍历右子树

代码:

void InOrder(BiTree root)  
{  
    if(root==NULL)  
        return ;  
    InOrder(root->lchild); //递归调用,中序遍历左子树  
    printf("%c ", root->data); //输出数据  
    InOrder(root->rchild); //递归调用,中序遍历右子树  
}  

2、非递归操作

代码:

void InOrderTraverse(BiTree T)   // 中序遍历的非递归  
{  
    if(!T)  
        return ;  
    stack<BiTree> S;  
    BiTree curr = T->lchild;    // 指向当前要检查的节点  
    S.push(T);  
    while(curr != NULL || !S.empty())  
    {  
        while(curr != NULL)    // 一直向左走  
        {  
            S.push(curr);  
            curr = curr->lchild;  
        }  
        curr = S.top();  
        S.pop();  
        cout<<curr->data<<"  ";  
        curr = curr->rchild;  
    }  
}  

 

posted @ 2013-04-09 18:13  一枚程序员  阅读(1514)  评论(1编辑  收藏  举报