非递归算法求二叉树高度

该文介绍了一种使用C++和队列容器实现的非递归算法,计算二叉树的高度。通过创建二叉链表结构,先序遍历输入数据,然后利用队列进行层次遍历来确定树的高度。
摘要由CSDN通过智能技术生成

假设二叉树采用二叉链表的存储结构,设计一个非递归算法求二叉树高度;

我这边用C++的队列容器解决。

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct BiNode {
    char data;
    struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
void create(BiTree& t) {//二叉树先序
    char ch;
    cin >> ch;
    if (ch == '@')t = NULL;
    else {
        t = new BiNode;
        t->data = ch;
        create(t->lchild);
        create(t->rchild);
    }
}
int Btdepth(BiTree t) {//使用C++容器
    queue<BiTree>q;
    BiTree last = NULL;
    int num = 0;
    BiTree p = t;
    q.push(p);
    last = q.back();
    while (!q.empty()) {
        p = q.front();
       
        
        if (p->lchild)q.push(p->lchild);
        if (p->rchild)q.push(p->rchild);
        if (p == last) {
            num++;
            last = q.back();
        }
        q.pop();//这个出队要放在这边,不能放在p = q.front();的下一行,因为如果在p = q.front();下一行
        //出队后容器可能为空,p == last的判断的前提是容器不为空。
        //使用容器的 top()、back()的使用,必须保证容器不为空


    }
    return num;
}
int main() {
    BiTree t;
    create(t);//测试数据:abd@@e@@c@@
    //abcde
    //edcba
    cout << Btdepth(t);
}

我重新又写了c语言的版本

#include<iostream>
using namespace std;
typedef struct BiNode {
    char data;
    struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
typedef struct stack {
    BiTree data[1024];
    int top;
}stack;
typedef struct queue {
    BiTree data[1024];
    int front;
    int rear;
}queue;
void create(BiTree& t) {//二叉树先序
    char ch;
    cin >> ch;
    if (ch == '@')t = NULL;
    else {
        t = new BiNode;
        t->data = ch;
        create(t->lchild);
        create(t->rchild);
    }
}
int Btdepth(BiTree T) {
      BiTree q[1024];
    int front = 0, rear = 0;
    BiTree p = T;
    q[rear++] = p;
    int level = 0;
    int last = rear;
    while (front < rear) {
        p = q[front++];
        if (p->lchild)q[rear++] = p->lchild;
        if (p->rchild)q[rear++] = p->rchild;
        if (front == last) {
            level++;
            last = rear;
        }
    }
    return level;
}
int main() {
    BiTree t;
    create(t);//测试数据:abd@@e@@c@@
    //abcde
    //edcba
    cout << Btdepth(t);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值