二叉树

#include <iostream>

extern "C"{
    #include <stdio.h>
    #include <stdlib.h>
}

using namespace std;

typedef struct BinTreeNode{
    char         cData;
    BinTreeNode* lNode;
    BinTreeNode* rNode;
}BinTreeNode;

char dataBuf[] = "ABDH#K###E##CFI###G#J##";
int index2 = 0;//注意此处全局变量不能使用index,index被库定义掉了

void createBinTree(BinTreeNode*& node)
{
    char data = dataBuf[index2++];
    if(data == '#')
        return;
    node = (BinTreeNode*)malloc(sizeof(BinTreeNode));
    if(node == NULL)
        return;
    node->cData = data;
    node->lNode = NULL;
    node->rNode = NULL;
    createBinTree(node->lNode);
    createBinTree(node->rNode);
}

void createBinTree2(BinTreeNode*& node)
{
    char data;
    cout << "input node value:";
    cin >> data;
    if(data == '0'){
        node = NULL;
        return;
    }
    node = (BinTreeNode*)malloc(sizeof(BinTreeNode));
    if(node == NULL){
        return;
    }
    node->cData = data;
    createBinTree2(node->lNode);//先序创建二叉树
    createBinTree2(node->rNode);
}

int treeDepth(BinTreeNode* node)
{
    int leftDepth,rightDepth;
    if(node == NULL){
        return 0;
    }
    else{
        leftDepth = treeDepth(node->lNode);
        rightDepth = treeDepth(node->rNode);
    }
    return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}

//横向打印树结构
void printBinTree(BinTreeNode* node,int depth)
{
    int iTemp = depth;
    if(node == NULL){
        return;
    }
    printBinTree(node->rNode,depth+1);
    while(--iTemp){
        cout << "  ";
    }
    cout << node->cData << endl;
    printBinTree(node->lNode,depth+1);
}

bool findData(BinTreeNode* node,char data)
{
    if(node == NULL)
        return false;
    if(node->cData == data){
        cout << "find the data " << data << endl;
        return true;
    }
    else{
        bool res = findData(node->lNode,data);
        if(res){
            return true;
        }
        else{
            res = findData(node->rNode,data);
            return res;
        }
    }
}

int main(int argc,char* argv[])
{
    BinTreeNode* node = NULL;
    createBinTree(node);
    printBinTree(node,1);
    cout << "########################" << endl;
    int depth = treeDepth(node);
    cout << "the tree depth:" << depth << endl;


    char data;
    cin >> data;
    bool res = findData(node,data);
    cout << (res?"found":"not found")<< endl;
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值