sundeepblue
4/24/2014 - 9:48 PM

Maximum Width of a Binary Tree

Maximum Width of a Binary Tree

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;
}