【数据结构·考研】二叉树的宽度

二叉树的最大宽度

求二叉树的宽度,我们首先想到他是广度(宽度)优先遍历的专利,记录每层结点数,取最大返回就是二叉树的宽度,如果我们想要用非递归的办法来解决的话,就需要设置一个数组来存储每层的结点数,然后引用一个 max 来记录最大结点数。这样的话就是相当于把非递归强行写成了递归,递归只起到了遍历的作用,所以此时更新 max 的时机可以是前中后任何一个地方。

代码如下:

#include<iostream>
#include<queue>
#include<vector>
using namespace std;

typedef struct node{
	char val;
	struct node* left;
	struct node* right;
}TreeNode,*Tree;

//非递归 
/*由根向下进行广度优先遍历,每遍历一层,记录该层宽度,最后返回最大的一个宽度*/ 
int maxWidth(Tree& t) {
    if(t == NULL) return 0;
    int max = 0; //树的最大宽度 
    queue<TreeNode*> q;
    q.push(t);
    while(!q.empty()){
        int width = q.size(); //本层宽度 
        for(int i = 0;i < width;i++){
            TreeNode* s = q.front();
            q.pop();
            if(s->left) q.push(s->left);
            if(s->right) q.push(s->right);
        }
        max = max > width ? max : width; //宽度更新 
    } 
    return max;
}

//递归 
void Width(Tree& t,int k,int* width,int& max){ //width[]是宽度数组,max在递归过程中记录最大宽度,k是层数 
    if(t == NULL)  return; //结点为空返回 
    width[k]++; //对应层数宽度+1 
    max = max < width[k] ? width[k] : max; //max更新 
    Width(t->left,k+1,width,max); //访问左子树 
    Width(t->right,k+1,width,max); //访问右子树 
}

void CreateTree(Tree& t){
	char x;
	cin>>x;
	if(x == '#') t = NULL; 
	else{
		t = new TreeNode; 
		t->val = x;  
		CreateTree(t->left); 
		CreateTree(t->right); 
	}
} 

void levelOrder(Tree& t) {
    if(t == NULL) return;
    queue<TreeNode*> q;
    q.push(t);
    while(!q.empty()){
        int n = q.size();
        for(int i = 0;i<n;i++){
            TreeNode* s = q.front();
            cout<<s->val<<" ";
            q.pop();
            if(s->left) q.push(s->left);
            if(s->right) q.push(s->right);
        }
        cout<<endl;
    } 
}

int main(){
	Tree t;
	CreateTree(t);
	/*
	   a b d # # e # # c f # # #
	*/
	levelOrder(t); 
	int max = 0;
	int width[3] = {0};
	cout<<endl<<"递归:"<<endl;
	Width(t,1,width,max);
	cout<<max;
	cout<<endl<<"非递归:"<<endl;
	cout<<maxWidth(t);
}

运行结果:

递归中的引用完全可以改为全局变量。

int count[100];
int max = -1
void Width(Tree& t,int k){
    if(t == NULL) return;
    count[k] ++;
    if(max < count[k]) max = count[k];
    Width(t->left,k+1);
    Width(t->right,k+1);
}

这样就看着舒服多了。

  • 16
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jiawen9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值