二叉树的前序遍历(包括树的定义与创建)

#include <cstdlib>
#include <iostream>
using namespace std;

struct BiTree           ///< 声明二叉树的结构
{             
    int    data;
    BiTree *left;
    BiTree *right;
};

// 插入节点值
BiTree* InsertNode(BiTree* pRoot,int node)   
{
     BiTree* pCurrNode;         ///< 声明目前节点指针
     BiTree* pParentNode;        ///< 声明父亲接点指针
     BiTree* pNewNode = new BiTree;      ///< 建立新节点的内存空间
     pNewNode->data=node;        ///< 存入节点的内容
     pNewNode->right=NULL;        ///< 设置右指针的初值
     pNewNode->left=NULL;        ///< 设置左指针的初值

     if(pRoot == NULL)
            return pNewNode;
     else{
            pCurrNode = pRoot;
            while(pCurrNode!=NULL){
                pParentNode = pCurrNode;
               (node<pCurrNode->data) ? pCurrNode = pCurrNode->left : pCurrNode =pCurrNode->right;  ///< 寻找空的节点便插入
            }         
            (pParentNode->data>node) ? pParentNode->left = pNewNode : pParentNode->right = pNewNode;  
    }
     return pRoot;
}

// 建立二叉树
BiTree* CreatBiTree(int data[],int len)
{
     BiTree* pRoot = NULL;        ///< 根节点指针
     for(int i=0; i<len; i++)       ///< 建立树状结构
         pRoot = InsertNode(pRoot,data[i]);
     return pRoot;
}

// 打印二叉树
void PrintBiTree(BiTree* pRoot)
{
     BiTree* pPointer = pRoot->left;
     if( pPointer!=NULL )
          printf("Left subtree node of root:/n");
     while(pPointer!=NULL){
          printf("[%2d]/n",pPointer->data);
          pPointer = pPointer->left;      ///< 指向左节点
     }
     pPointer = pRoot->right;
     if( pPointer!=NULL )
          printf("Right subtree node of root:/n");
     while(pPointer!=NULL){
          printf("[%2d]/n",pPointer->data);    ///< 打印节点的内容
          pPointer = pPointer->right;      ///< 指向右节点
     }
}

// 前序遍历

void PreOder(BiTree* pPointer)
{
     if(pPointer!=NULL){
            cout << pPointer->data<<" ";
            PreOder(pPointer->left);
            PreOder(pPointer->right);      ///< 节点--左子树--右子树
     }
}

// 释放资源
void Release(BiTree* pRoot)
{
    if( pRoot==NULL )
        return;

    Release(pRoot->left);
    Release(pRoot->right);
    delete pRoot;
    pRoot = NULL;
}

void main()
{
    BiTree* pRoot = NULL;
    int index=0,value;
    int nodelist[100] = {0};
 
    printf("Please input the elements of binary tree (Exit for 0):/n");
    scanf("%d",&value);
    while (value!= 0){
        nodelist[index++] = value;
        scanf("%d",&value);
    }
    pRoot = CreatBiTree(nodelist,index);    ///< 建立二叉树
    PrintBiTree(pRoot);         ///< 打印二叉树节点的内容
    cout <<"/nThe preoder travesal result is:"<<endl;
    PreOder(pRoot);
    cout<<endl<<endl;

    Release(pRoot);          ///< 释放资源
}

你可能感兴趣的:(二叉树)