/**************************************************
* 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;
}求二叉树宽度(度娘)
最新推荐文章于 2022-10-26 14:24:38 发布
本文介绍了一种计算二叉树宽度的方法,通过递归遍历并记录左右坐标来确定二叉树的最大宽度。
796

被折叠的 条评论
为什么被折叠?



