1. 程式人生 > >資料結構-二叉樹-建立,輸出,計算長度-C++

資料結構-二叉樹-建立,輸出,計算長度-C++

#include<iostream>
#include<stdlib.h>

using namespace std;

typedef struct BTNode BTNode;

struct BTNode{ 
    int ch;
    BTNode * left;
    BTNode * right;
};
// 建立一個二叉樹 先序輸入 0表示NULL 
BTNode * creatBTNode(){
    BTNode * p;
    int ch;
    cin>>ch;

    if(ch ==0){
        p=NULL;
    }
    else
{ p=(BTNode *)malloc(sizeof(BTNode)); p->ch=ch; p->left=creatBTNode(); p->right=creatBTNode(); } return p; } //*****************先序遍歷************ void preOrderTraverse(BTNode * node){ if(node){ cout<<node->ch<<' '; preOrderTraverse(node->left); preOrderTraverse(node->right); } } //******************中序遍歷**********
void inOrderTraverse(BTNode * node){ if(node){ inOrderTraverse(node->left); cout<<node->ch<<' '; inOrderTraverse(node->right); } } //*****************後序遍歷輸出******* void lastOrderTraverse(BTNode * node){ if(node){ lastOrderTraverse(node->left); lastOrderTraverse(node->right); cout
<<node->ch<<' '; } } //****************二叉樹節點數目****** int NodeNum(BTNode * node){ if(node==NULL){ return 0; } else{ return 1+NodeNum(node->left)+NodeNum(node->right); } } //*************二叉樹深度************* int DepthOfTree(BTNode * node){ if(node){ return DepthOfTree(node->left)>DepthOfTree(node->right)?DepthOfTree(node->left)+1:DepthOfTree(node->right)+1; } if(node==NULL){ return 0; } } //**************二叉樹葉子節點數******* int leafNum(BTNode * node){ if(!node){ return 0; } else if(node->left==NULL&&node->right==NULL){ return 1; } else{ return (leafNum(node->left)+leafNum(node->right)); } } int main(){ BTNode * bttree=creatBTNode(); cout<<"先序遍歷輸出:"<<endl; preOrderTraverse(bttree); cout<<"\n中序遍歷輸出:"<<endl; inOrderTraverse(bttree); cout<<"\n後序遍歷輸出:"<<endl; lastOrderTraverse(bttree); cout<<"\n二叉樹節點數目:"<<endl; cout<<NodeNum(bttree)<<endl; cout<<"二叉樹深度"<<endl; cout<<DepthOfTree(bttree)<<endl; cout<<"葉子節點數"<<endl; cout<<leafNum(bttree)<<endl; return 0; }

原文:http://blog.csdn.net/ricardo_he/article/details/41119709