yxjxx
1/20/2015 - 1:23 PM

calc_bintree_leaf_num.cpp

#include <iostream>
#include <iomanip>

using namespace std;

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



void CreateBinTree(BinTree &T){
    T->data = 'a';
    T->lchild = NULL;
    T->rchild = NULL;

    T->lchild = (BTNode *) malloc(sizeof(BTNode));
    T->lchild->data = 'b';
    T->lchild->lchild = NULL;
    T->lchild->rchild = NULL;

    T->rchild = (BTNode *) malloc(sizeof(BTNode));
    T->rchild->data = 'c';
    T->rchild->lchild = NULL;
    T->rchild->rchild = NULL;

    T->lchild->lchild = (BTNode *) malloc(sizeof(BTNode));
    T->lchild->lchild->data = 'd';
    T->lchild->lchild->lchild = NULL;
    T->lchild->lchild->rchild = NULL;

    T->lchild->rchild = (BTNode *) malloc(sizeof(BTNode));
    T->lchild->rchild->data = 'e';
    T->lchild->rchild->lchild = NULL;
    T->lchild->rchild->rchild = NULL;

    T->rchild->lchild = (BTNode *) malloc(sizeof(BTNode));
    T->rchild->lchild->data = 'f';
    T->rchild->lchild->lchild = NULL;
    T->rchild->lchild->rchild = NULL;

    T->rchild->rchild = (BTNode *) malloc(sizeof(BTNode));
    T->rchild->rchild->data = 'g';
    T->rchild->rchild->lchild = NULL;
    T->rchild->rchild->rchild = NULL;

    //新建节点之后要把指针域赋NULL
}

int calc_leaf_num(BinTree T){
    if(T->lchild != NULL && T->rchild != NULL){
        return calc_leaf_num(T->lchild)+ calc_leaf_num(T->rchild);
    }
    if(T->lchild != NULL && T->rchild == NULL){
        return calc_leaf_num(T->lchild);
    }
    if(T->lchild == NULL && T->rchild != NULL){
        return calc_leaf_num(T->rchild);
    }
    if(T->lchild == NULL && T->rchild == NULL){
        return 1;
    }
}

int main()
{

    BinTree T = (BTNode *) malloc(sizeof(BTNode));
    CreateBinTree(T);

    cout << calc_leaf_num(T);

    return 0;
}