二叉树的遍历

来源:互联网 发布:php网站破解工具 编辑:程序博客网 时间:2024/06/04 01:11

包括二叉树的递归前、中、后序,以及非递归前序


#include<iostream>

#include<cstdio>
#include<cstdlib>
#include<cstring>
using std::cin;
using std::cout;
using std::endl;
//using std::stack;
using namespace std;


typedef struct BTNode
{
    char data;
    BTNode *lchild;
    BTNode *rchild;
}BTNode;


void PreRecurTraversal(BTNode *bt)//先序递归
{
    if(bt != NULL)
    {
        cout<<bt->data<<" ";
        PreRecurTraversal(bt->lchild);
        PreRecurTraversal(bt->rchild);
    }
}


void MidRecurTraversal(BTNode *bt)//中序递归
{
    if(bt != NULL)
    {
        MidRecurTraversal(bt->lchild);
        cout<<bt->data<<" ";
        MidRecurTraversal(bt->rchild);
    }
}


void PostRecurTraversal(BTNode *bt)//后序递归
{
    if(bt != NULL)
    {
        MidRecurTraversal(bt->lchild);
        MidRecurTraversal(bt->rchild);
        cout<<bt->data<<" ";
    }
}




/*void PreTraversalOne(BTNode *bt)//前序非递归遍历
{
    BTNode  *pbt = bt;
    std::stack<BTNode*> s;
    while(!s.empty()|| pbt != NULL)
    {
        while(pbt != NULL)
        {
            cout<<pbt->data;
            s.push(pbt);
            pbt = pbt->lchild;
        }
        if(!s.empty())
        {
            pbt = s.top();
            s.pop();
            pbt = pbt->rchild;
        }
    }
}*/


BTNode* createBTNode() //建立二叉树
{
    char c;
    BTNode* bt = NULL;
    if((c = getchar()) == ',')
        bt = NULL;
    else
    {
        bt = (BTNode*)malloc(sizeof(BTNode));
        bt->data = c;
        bt->lchild = createBTNode();
        bt->rchild = createBTNode();
    }
    return bt;
}


int TreeDepth(BTNode* pRoot)
{
    if(pRoot == NULL)
        return 0;


    int nLeft = TreeDepth(pRoot->lchild);
    int nRight = TreeDepth(pRoot->rchild);


    return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}


int main()
{
    BTNode * bt = NULL;
    bt = createBTNode();
    PreRecurTraversal(bt);
    cout<<TreeDepth(bt)<<endl;
    return 0;
}

0 0
原创粉丝点击