求二叉树宽度(度娘)

本文介绍了一种计算二叉树宽度的方法,通过递归遍历并记录左右坐标来确定二叉树的最大宽度。
/**************************************************
 * file:cal_binary_tree_width.c
 * brief:calculate the width of a binary
 * yejing@2015.1.14    1.0
 **************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _node_{
	struct _node_* left;
	struct _node_* right;
	int            key;
}node_t;

static int current_right_coordinate = 0;
static int current_left_coordinate = 0;

void calculate_width_of_binary_tree(node_t* root, int coordinate) {
	if(!root)
		return;
	int tmp = coordinate;

	if(root->left){
		if(--tmp < current_left_coordinate)
			current_left_coordinate = tmp;
		calculate_width_of_binary_tree(root->left, tmp);
	}

	if(root->right){
		if(++coordinate > current_right_coordinate)
			current_right_coordinate = coordinate;
		calculate_width_of_binary_tree(root->right, coordinate);
	}

	return;
}

node_t* build_a_binary_tree(void){
	char need_left_child, need_right_child;

	node_t* root = (node_t*)malloc(sizeof(node_t));
	if(!root)
		return NULL;

	memset((char*)root, 0, sizeof(node_t));

	printf("do you need a left child, y confirm\n");
	scanf("%c", &need_left_child);
	getchar();
	if(need_left_child == 'y')
		root->left = build_a_binary_tree();

	printf("do you need a right child, y confirm\n");
	scanf("%c", &need_right_child);
	getchar();
	if(need_right_child == 'y')
		root->right = build_a_binary_tree();

	return root;
}

int main(int argc, char* argv[]){
	node_t* root = build_a_binary_tree();
	if(!root)
		return;
	calculate_width_of_binary_tree(root, 0);
	printf("the width of the tree is %d \n", 1 + current_right_coordinate - current_left_coordinate);
	return 1;
}

### 二叉树高度和宽度的计算方法 #### 一、二叉树的高度计算 二叉树的高度是指从根节点到最远叶子节点路径上的边的数量。可以通过递归的方式实现,具体逻辑如下: 如果当前节点为空,则其高度为0;否则分别递归计算左子树和右子树的高度,并取两者中的较大值加1作为当前节点的高度。 以下是基于C语言的实现代码: ```c int BiTreeDepth(BiTree T) { if (T == NULL) return 0; int depthLeft = BiTreeDepth(T->lchild); // 左子树的高度 int depthRight = BiTreeDepth(T->rchild); // 右子树的高度 return 1 + (depthLeft > depthRight ? depthLeft : depthRight); } ``` 此算法的时间复杂度为O(n),其中n为二叉树中节点的数量[^1]。 --- #### 二、二叉树宽度计算 二叉树宽度定义为某一层具有最多节点数的那一层的节点数量。可以采用两种方式来实现这一目标:递归法或层次遍历法。 ##### 方法1:递归法 通过递归统计每一层的节点数并记录最大值。以下是一个具体的实现方案: 1. 使用一个数组`a[]`保存每层的节点数; 2. 调用辅助函数`WidthR()`递归更新该数组; 3. 找到数组的最大值即为二叉树宽度。 下面是对应的C语言代码: ```c void WidthR(BiTree T, int a[], int i) { if (T != NULL) { a[i]++; WidthR(T->lchild, a, i + 1); WidthR(T->rchild, a, i + 1); } } int Width(BiTree T) { if (T == NULL) return 0; int high = BiTreeDepth(T); // 获取二叉树的高度 int length[high + 1]; for (int i = 0; i <= high; i++) { length[i] = 0; // 初始化数组length } WidthR(T, length, 0); int max = length[0]; // 初始设第0层为最大值 for (int i = 1; i <= high; i++) { if (max < length[i]) { max = length[i]; } } return max; } ``` 这种方法同样依赖于递归来完成层数计数的任务,时间复杂度也为O(n)[^1]。 ##### 方法2:层次遍历法 另一种更直观的方法是利用队列进行广度优先搜索(BFS),逐层扫描整个二叉树,在过程中维护当前层的最大节点数即可得到最终的结果。 下面展示了一个类似的思路实现: ```cpp #include <queue> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; }; int widthOfBinaryTree(TreeNode* root) { if (!root) return 0; queue<pair<TreeNode*, unsigned long>> q; q.push({root, 0}); unsigned long maxWidth = 0; while (!q.empty()) { int size = q.size(); unsigned long firstIndex, lastIndex; for (int i = 0; i < size; ++i) { auto [node, index] = q.front(); q.pop(); if (i == 0) firstIndex = index; if (i == size - 1) lastIndex = index; if (node->left) q.push({node->left, 2 * index + 1}); if (node->right) q.push({node->right, 2 * index + 2}); } maxWidth = max(maxWidth, lastIndex - firstIndex + 1); } return maxWidth; } ``` 这段代码采用了无符号整型变量以防止索引溢出问题,并且能够处理极端情况下的宽度过大情形[^2]。 --- #### 总结 无论是二叉树的高度还是宽度,都可以借助递归或者迭代的思想来进行操作。对于高度而言,通常推荐使用简单的递归形式;而对于宽度来说,虽然也可以采取递归手段,但在实际应用当中更多时候会选择效率更高的层次遍历技术[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值