其他分享
首页 > 其他分享> > leetcode-107. 二叉树的层序遍历 II

leetcode-107. 二叉树的层序遍历 II

作者:互联网

leetcode-107. 二叉树的层序遍历 II

题目

在这里插入图片描述

代码

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

typedef struct TreeNode{
	int val;
	struct TreeNode *left,*right;
}TreeNode,*BiTree;

void create(BiTree &T){
	char ch;
	cin>>ch;
	if(ch=='#'){
		T=NULL;
		return;
	}
	T=new TreeNode;
	T->val=ch-'0';
	create(T->left);
	create(T->right);
}

vector<vector<int> > levelOrderBottom(TreeNode* root) {
	vector<vector<int> > res;
	if(!root){
		return res;
	}
	queue<TreeNode *>q;
	q.push(root);
	while(!q.empty()){
		vector<int> lever;
		int size=q.size();
		for(int i=0;i<size;i++){
			TreeNode *T=q.front();
			q.pop();
			lever.push_back(T->val);
			if(T->left){
				q.push(T->left);
			}
			if(T->right){
				q.push(T->right);
			}
		}
		res.push_back(lever);
	}
	reverse(res.begin(),res.end());
	return res;
}

int main(){
	vector<vector<int> >res; 
	TreeNode* root;
	create(root);
	res=levelOrderBottom(root);
	for(int i=0;i<res.size();i++){
		for(int j=0;j<res[i].size();j++){
			cout<<res[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}

标签:right,TreeNode,int,res,层序,二叉树,push,root,107
来源: https://blog.csdn.net/qq_42250642/article/details/121363054