c_cpp 二叉树的最大宽度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 二叉树的最大宽度相关的知识,希望对你有一定的参考价值。

int height(TreeNode *root) {
    if(!root) return 0;
    int lh = height(root->left), rh = height(root->right);
    return lh > rh ? lh + 1 : rh + 1;
}

int get_width_at_level(TreeNode *root, int level) {
    if(!root) return 0;
    if(level == 1) return 1;
    return get_width_at_level(root->left, level-1) + get_width_at_level(root->right, level-1);
}

int get_max_width(TreeNode *root) {
    if(!root) return 0;
    int h = height(root);
    int max_width = 0;
    for(int i=0; i<h; i++) {
        max_width = max(max_width, get_width_at_level(root, i);
    }
    return max_width;
}

以上是关于c_cpp 二叉树的最大宽度的主要内容,如果未能解决你的问题,请参考以下文章