VC++6.0程序设计系列:[1]二叉树的实现

2025-10-16 16:40:32

1、创建一个控制台项目,项目的名称自己定义。

VC++6.0程序设计系列:[1]二叉树的实现

2、添加cpp文件,到刚才新建的工程中。

VC++6.0程序设计系列:[1]二叉树的实现

3、在新添加的文件中,编写相应的代码。代码比较简单,没有想象的复杂。

#include <iostream>using namespace std ;struct Node{    int data ;    Node* left ;    Node* right ;    Node():data(0){left =NULL ; right =  NULL;}    Node(int d):data(d) {left =NULL ; right =  NULL;}};class BTree{public:    Node * root ;    BTree(){root = NULL;}    BTree(int ds[],int n):root(NULL){        root = NULL;        createBTree(ds,n) ;    }    void createBTree(int ds[],int n){        for(int i = 0 ; i<n;i++){            insertNode(root,ds[i]) ;        }    }    void insertNode(Node*& root,int d){//插入节点        if(root == NULL){            root = new Node(d) ;            return ;        }        if(root->data>d){            if(root->left==NULL)root->left = new Node(d) ;            else insertNode(root->left,d) ;        }else {            if(root->right==NULL)root->right = new Node(d) ;            else insertNode(root->right,d) ;        }    }    void prePrint(Node * rt){//先根序输出        if(rt==NULL)return;        cout<<rt->data<<" ";        prePrint(rt->left) ;        prePrint(rt->right) ;    }};int main(){    int ds[]={1,2,3,4,5,6,7,8,9} ;    BTree bt(ds,sizeof(ds)/sizeof(int)) ;    bt.prePrint(bt.root) ;    return 0 ;}

VC++6.0程序设计系列:[1]二叉树的实现

4、调试,运行

VC++6.0程序设计系列:[1]二叉树的实现

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢