计算二叉链表存储的二叉树的深度(递归与非递归)

typedef struct BiTree{
    struct BiTree* lchild;
    struct BiTree* rchild;
    int data;
}BiTree;

typedef struct Queue{
    int front;
    int rear;
    BiTree* data[MaxSize];
}Queue;

void CreateTree(BiTree* &node){
    int data;
    cout<<"please input data: "<<endl;
    cin>>data;
    if (data != -1) {
        node = new BiTree();
        node->data = data;
        CreateTree(node->lchild);
        CreateTree(node->rchild);
    }
}

int deepth(BiTree* tree){
    if (tree == NULL) {
        return 0;
    }
    int left = deepth(tree->lchild);
    int right = deepth(tree->rchild);
    return left>right?left+1:right+1;
}

int deepthNoRecur(BiTree* tree){
    if(tree == NULL){
        return 0;
    }
    BiTree* bit;
    Queue queue;
    int level = 0;
    queue.front = 0;
    queue.rear = 0;
    queue.data[queue.rear] = tree; // 根结点入栈
    queue.rear = (queue.rear + 1) % MaxSize;
    while (queue.front!=queue.rear) {
        level++;
        int size = (queue.rear-queue.front+MaxSize) % MaxSize;
        while (size--) {
            bit = queue.data[queue.front++];
            if (bit->lchild!=NULL) {
                   queue.data[queue.rear] = bit->lchild;
                   queue.rear = (queue.rear + 1) % MaxSize;
            }
            if (bit->rchild!=NULL) {
                   queue.data[queue.rear] = bit->rchild;
                   queue.rear = (queue.rear + 1) % MaxSize;
            }
        }
    }
    return level;
}
  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值