力扣107. 二叉树的层次遍历 II(层序遍历,队列,广度优先算法,BFS)
https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
层序遍历,队列,广度优先算法,BFS
//层序遍历,队列,广度优先算法,BFS
#include "stdafx.h"
#include<queue>
#include<vector>
#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrderBottom(TreeNode* root)
{
int curcount = 0;
int nextcount = 1;
int depth = 0;
vector<int>valtemp;
vector<vector<int>>resulttemp;
vector<vector<int>>result;
queue<TreeNode*>que;
//头结点为空,直接返回空数组
if (root == nullptr)return result;
que.push(root);
while (!que.empty())
{
TreeNode* tempnode = que.front(); que.pop();
curcount++;
//对于每一个值,先暂存起来
valtemp.push_back(tempnode->val);
if (tempnode->left != nullptr)que.push(tempnode->left);
if (tempnode->right != nullptr)que.push(tempnode->right);
if (curcount == nextcount)
{
//一层存一次
resulttemp.push_back(valtemp);
valtemp.clear();
curcount = 0;
depth++;
nextcount = que.size();
}
}
//自底向上,翻转数组
for (int i = depth - 1; i >= 0; i--)
{
result.push_back(resulttemp[i]);
}
return result;
}
};
int main()
{
TreeNode p[13] = { 2,3,3,4,5,5,4,NULL,NULL,8,9,9,8 };
p[0].left = &p[1]; p[0].right = &p[2];
p[1].left = &p[3]; p[1].right = &p[4];
p[2].left = &p[5]; p[2].right = &p[6];
//p[3].left = &p[7]; p[3].right = &p[8];
p[4].left = &p[9]; p[4].right = &p[10];
p[5].left = &p[11]; p[5].right = &p[12];
Solution s;
auto result = s.levelOrderBottom(p);
for (int i = 0; i < result.size(); i++)
{
for (int j = 0; j < result[i].size(); j++)
{
cout << result[i][j] << '\t';
}
cout << '\n';
}
return 0;
}