使用预序遍历的二叉树的最大宽度
Maximum width of a Binary Tree using preorder traversal
我想要得到二叉树的最大宽度。在这种方法中利用预阶可以计算遍历宽度。但我不能完全理解它。请解释函数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
的树的宽度。
相关文章:
- 二叉树级别顺序遍历在leetcode中
- 使用二叉树的关卡顺序概念的垂直顺序遍历
- 之字折线二叉树遍历C++
- 二叉树级别顺序遍历 LeetCode
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 二叉树顺序遍历在C++
- C++,如何创建和绘制二叉树,然后按预购方式遍历它
- 二叉树顺序遍历错误:没有用于调用的匹配函数
- 基于矢量的二叉树遍历
- 这种遍历二叉树的递归方法在一些递归后崩溃!为什么?
- 如何遍历二叉树并在不传递值的情况下计算值的出现次数
- 使用递归的顺序二叉树遍历与使用堆栈的优缺点
- 从序遍历和预序遍历构造二叉树的时间复杂性
- 使用级别顺序遍历将节点插入二叉树
- 递归后序遍历解除分配二叉树节点
- C++中的可变与不可变二叉树遍历
- 从给定的预序遍历构建二叉树
- 四叉树遍历
- 如何在二叉树遍历的末尾添加一行新代码
- C++中的一个迭代二叉树遍历