weixin_52463018 2021-11-15 18:49 采纳率: 100%
浏览 45
已结题

数据结构(c++语言)求二叉树的宽度

img

  • 写回答

1条回答 默认 最新

  • 关注

    参考:

    #include<iostream>
    #include<stdlib.h> 
    #include<deque>  //插入标准库中的头文件
    using namespace std;
     
    typedef struct treenode
    {
        char data;
        treenode *right;
        treenode *left;
    }*Node;
     
    //创建二叉树
    void creat_tree(treenode *&rt)
    {
        char ch;
        ch = getchar();
        if ('#' == ch) {
            rt = NULL;
        } else {
            rt = new treenode;
            rt->data = ch;
            creat_tree(rt->left);        //构造左子树
            creat_tree(rt->right);    //构造右子树    
        }
    }
     
    //层次遍历
    void Complete_binary_tree(treenode *&root,int &height,int &width) { //在这里采用层次遍历的方法
        if (root == NULL) { //空树满足条件
            height = 0;
            width = 0;
        }
     
        int max = -1; height = 0; width = 0;
        Node last = root;
        deque <Node> c;  //定义一个空的队列
        c.push_back(root);
        while (!c.empty()) {  //如果队列不为空
            Node temp = c.front();  //返回队列的第一个元素
            width++;  //宽度加1
            if (temp) {  //如果是非空结点
                cout << temp->data << " ";
                c.pop_front();  //出队列
     
                if (temp->left) {
                    c.push_back(temp->left);  //左孩子
                }
                if (temp->right) {
                    c.push_back(temp->right); //右孩子
                }
     
                if (temp == last ) { //访问到最右边的非空节点
                    if (!c.empty()) {
                        last = c.back();  //重新赋值
                    }
                    height++;  //高度加1
                    //接下来判断宽度
                    if (width >= max) {
                        max = width;
                        width = 0;  //重新计数
                    }
                }
            }
        }
        width = max;
    }
     
    int main() {
        treenode *root = NULL;
        int height, width;  //表示高度和最大宽度
        cout << "请输入二叉树,空值以#代表:" << endl;
        creat_tree(root);        //创建二叉树
        Complete_binary_tree(root,height,width);
        cout << "高度为:" << height << endl;
        cout<<"最大宽度为:" << width << endl;
        system("pause");
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月31日
  • 已采纳回答 12月23日
  • 创建了问题 11月15日

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装
  • ¥40 复杂的限制性的商函数处理