leiyahui

纸上得来终觉浅,绝知此事要躬行
二叉树遍历的应用

1 利用前序二叉树非递归遍历对二叉树中的各类节点进行统计

  void PreOrderc(BTptr T,int* n0,int* n1,int* n2)
{
    int n0;
    int n1;
    int n2;
    n0=n1=n2=0;
    BTptr p;
    ClearStack(s);
    push(s,p);
    while(!EmptyStack())
    {
        p=Pop(s);
        while(p)
        {
            visit(p);
            if(p->LChild&&p->RChild)
            {
                n2++;
                Push(s,p->RChild);
                p=p->LChild;
            }
            else if(p->LChild||p-RChild)
            {
                n1++;
                if(p->LChild)
                {
                    p=p->LChild;
                }
                else
                {
                    p=p->RChild;
                }
            }
            else
            {
                p=NULL;
                n0++;
            }
        }
    }
}

二 求二叉树的深度

这个问题比较难一点,要在增加一个栈来存放另一这个栈中对应节点的层数,并且设置一个Max变量,来存储当前遍历的最大层数。

void InorderDept(BTptr T)
{
    int Max=0;
    int i=1;
    BTptr p=T;
    ClearStack(s1);
    ClearStack(s2);
    Push(s1,T);
    Push(s2,1);
    if(p||!EmptyStack(p))
    {
        while(p)
        {
            p=p->LChild;
            i++;
            Push(s1,p);
            Push(s2,i);
        }
        p=Pop(s1);
        i=Pop(s2);
        if(p->RChild)    //到叶节点时与最大值比较
        {
            if(i>Max)
            Max=i;
        }
        p=p->RChild;
        i++:
    }
}

 

posted on 2015-11-22 19:55  雷大叔  阅读(270)  评论(0)    收藏  举报