提示:君子道长,小人道消
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]、
既然是找每一层的 这里依然是使用层序遍历 只需要稍作修改便可 使用一个max来保留最大值 这里直接写出代码
#include<bits/stdc++.h>
#define ElemType int
using namespace std;
typedef struct BiNTree{
struct BiNTree* Lchild;
ElemType data;
struct BiNTree* Rchild;
}BiNTree;
/*层序的思想是,首先需要判断此时第一个元素是否为空 为此
若是为空就不用需要进入树队中了 若是第一个元素不为空 则进入队列中
然后为其分配左右子树,若是值为-1 则表示此时的孩子为空 不需要入队
若是值不为-1 ,让其作为此时结点的孩子,然后此孩子入队
直到元素值队列为空*/
void Creat(BiNTree* &T){
int val;
BiNTree* cur;//定义一个cur
queue<ElemType> Q;
queue<BiNTree*> TreeQue;
cout<<"请输入层序遍历的序列"<<endl;
while(scanf("%d",&val)!=EOF) Q.push(val);
if(Q.front()==-1){
cout<<"树为空"<<endl;
T=NULL;
return ;
}
else{
T=(BiNTree*)malloc(sizeof(BiNTree));
T->data=Q.front();
TreeQue.push(T);
}
Q.pop();
while(!Q.empty()){//我们每一次处理 处理的都是左右孩子,所以也就需要两个if
cur=TreeQue.front();//取出此时树队中的第一元素
if(Q.front()==-1){//此时这个结点值为NULL
cout<<cur->data<<"左孩子为空"<<endl;
cur->Lchild=NULL;
}
else{//新生成一个树结点用来存放此时的结点信息
cout<<cur->data<<"左孩子为"<<Q.front()<<endl;
cur->Lchild=(BiNTree*)malloc(sizeof(BiNTree)) ;
cur->Lchild->data=Q.front();
TreeQue.push(cur->Lchild);
}
Q.pop();//处理完数据之后需要弹出 来取此结点右子树的值
//上面的if else 是处理结点左孩子 下面我们来处理右孩子
if(Q.front()==-1){
cout<<cur->data<<"右孩子为空"<<endl;;
cur->Rchild=NULL;
}
else{
cout<<cur->data<<"右孩子为"<<Q.front()<<endl;
cur->Rchild=(BiNTree*)malloc(sizeof(BiNTree));
cur->Rchild->data=Q.front();
TreeQue.push(cur->Rchild);
}
Q.pop();
TreeQue.pop();
}
}
void LevelOrder(BiNTree* T){//这里我们是使用的是队列来完成这个操作
queue<BiNTree*> Q; BiNTree* cur;
if(T==NULL){//跟前面一样 若是为空则不需要进队 直接返回即可
return ;
}
Q.push(T);
while(!Q.empty()){
int max=Q.front()->data;//别忘了使用这一行的第一个值来进行初始化
int size=Q.size();//需要一个值来保存 因为Q.size 是一直变得
for(int i=0;i<size;i++){
cur=Q.front();
max= cur->data>max?cur->data:max;
if(cur->Lchild) Q.push(cur->Lchild);
if(cur->Rchild) Q.push(cur->Rchild);
Q.pop();
}
//每一次for之后这层的容器收集的结果要放在总的栈中
printf("%d\n",max);
}
}
main(){
int i=0;
BiNTree* T=NULL;
vector<vector<int>> result;
Creat(T);
cout<<"此时树的m每一层的最大值是"<<endl;
LevelOrder(T);
}