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

二叉树的最大宽度

求二叉树的宽度,我们首先想到他是广度(宽度)优先遍历的专利,记录每层结点数,取最大返回就是二叉树的宽度,如果我们想要用非递归的办法来解决的话,就需要设置一个数组来存储每层的结点数,然后引用一个 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);
}

这样就看着舒服多了。

猜你喜欢

转载自blog.csdn.net/cjw838982809/article/details/108266532