程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++編寫數據結構中的二叉樹(前序,中序,後序遍歷)

C++編寫數據結構中的二叉樹(前序,中序,後序遍歷)

編輯:C++入門知識

編譯環境xCode 5.1

Two.h:

#ifndef __OK__Two__
#define __OK__Two__

#include 
typedef struct List{
    char name[20];
    char desc[200];
    int num;
    List *next;
}List;


typedef struct myTree{
    int data;
    char stu_name[20];
    char desc[200];
    int num;
    myTree *lChild;
    myTree *rChild;
}tree;


class listtree {
    
public:
    void createTree(int,int[],char*[]);
    void preOrder(tree *);//前序遍歷
    void inOrder(tree *);//中序遍歷
    void postOrder(tree *);//後序遍歷
    myTree *rootNode;
};


#endif /* defined(__OK__Two__) */

Two.cpp

#include "Two.h"
void listtree::createTree(int count,int num[],char *names[]){
    int index = count;
    tree *currentNode = NULL;
    while (index) {
        tree *node = new tree;
        int id = count-index;
        node->data = num[id];
        strcpy(node->stu_name, names[id]);
        node->lChild = NULL;
        node->rChild = NULL;
        if (rootNode==NULL) {
            rootNode = node;
            
        }else{
            currentNode = rootNode;
            tree *thisNode = NULL;
            while (currentNode!=NULL) {
                thisNode = currentNode;
                if (currentNode->data>node->data) {
                    currentNode = currentNode->lChild;
                }else {
                    currentNode = currentNode->rChild;
                }
            }
            if(node->data>thisNode->data){
                thisNode->rChild = node;
            }else{
                thisNode->lChild = node;
            }
            currentNode = node;
        }
        index--;
    }
}
void listtree::preOrder(tree *node){
    if (node==NULL) {
        return;
    }
    std::cout<data<<"++"<stu_name<<"++"<<"\n";
    preOrder(node->lChild);
    preOrder(node->rChild);
}
void listtree::inOrder(tree *node){
    if (node==NULL) {
        return;
    }
    inOrder(node->lChild);
    std::cout<data<<"++"<stu_name<<"++"<<"\n";
    inOrder(node->rChild);
}
void listtree::postOrder(tree *node){
    if (node==NULL) {
        return;
    }
    postOrder(node->lChild);
    postOrder(node->rChild);
    std::cout<data<<"++"<stu_name<<"++"<<"\n";
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved