uicccui 2021-11-24 18:56 采纳率: 42.9%
浏览 83
已结题

数据结构与算法“play with tree”

Given a binary tree, your task is to get the height and size(number of nodes) of the tree.
The Node is defined as follows.

struct Node {
Node *lc, *rc;
char data;
};

Implement the following function.

void query(const Node *root, int &size, int &height)
{
// put your code here
}

提示

In this problem, we assume that the height of the tree with only one node is 1.

求完整代码

  • 写回答

1条回答 默认 最新

  • 广大菜鸟 2021-11-25 01:06
    关注
    
    #include<iostream>
    using namespace std;
    
    #define max(a,b) ((a)>(b)?(a):(b))
    
    struct Node {
        struct Node* lc, * rc;
        char data;
    };
    
    void query(const Node* root, int& size, int& height) {
        if (root == NULL) return;
        int leftHeight = 0, rightHeight = 0;
        query(root->lc, size, leftHeight);
        query(root->rc, size, rightHeight);
        size += 1;
        height = 1 + max(leftHeight, rightHeight);
    }
    
    int main() {
        //测试案例:
        //            root 
        //        lc            rc
        Node* root = (Node*)malloc(sizeof(Node));
        if (root != NULL) {
            root->rc = (Node*)malloc(sizeof(Node));
            if (root->rc != NULL) {
                root->rc->lc = root->rc->rc = NULL;
            }
    
            root->lc = (Node*)malloc(sizeof(Node));
            if (root->lc != NULL) {
                root->lc->lc = root->lc->rc = NULL;
            }
        }
        int size = 0, height = 0;
        query(root, size, height);
        cout << size << "\t" << height << endl;
    }
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月8日
  • 已采纳回答 11月30日
  • 创建了问题 11月24日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵