使用预序遍历的二叉树的最大宽度

Maximum width of a Binary Tree using preorder traversal

本文关键字:二叉树 遍历      更新时间:2023-10-16

我想要得到二叉树的最大宽度。在这种方法中利用预阶可以计算遍历宽度。但我不能完全理解它。请解释函数getMaxWidthRecur()是如何工作的。

// A utility function that returns maximum value in arr[] of size n
    int getMax(int arr[], int n);
/* A function that fills count array with count of nodes at every
   level of given binary tree*/
    void getMaxWidthRecur(struct node *root, int count[], int level);
// Function to get the maximum width of a binary tree
    int getMaxWidth(struct node* root){
    int h = height(root);
    // Create an array that will store count of nodes at each level
    int *count = (int *)calloc(sizeof(int), h);
    int level = 0;
    // Fill the count array using preorder traversal
    getMaxWidthRecur(root, count, level);
    // Return the maximum value from count array
    return getMax(count, h);
}
// A function that fills count array with count of nodes at every
// level of given binary tree
void getMaxWidthRecur(struct node *root, int count[], int level){
    if(root){
         count[level]++;
         getMaxWidthRecur(root->left, count, level+1);
         getMaxWidthRecur(root->right, count, level+1);
    }
}

主要工作正在getMaxWidthRecur中完成。它最初的参数是level = 0。每当我们在树中向下递归一层时,level参数就增加1。递归将恰好击中树中的每个节点一次,并且对于树中的每个节点,它将count[level]加1。因此,当它耗尽树中的所有节点时,count[i]将等于深度为i的树的宽度。