题目来源:leetcode
原题地址:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
题目:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
难度级别:
easy(容易)
思路分析:
此题较为简单,采用队列的数据结构就可以很轻松的解决此题。
相对于层序遍历,这里要求对每一层的个数做一下记录就可以了。
然后一层一层遍历就可以完成此题。
实现代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution
{
public:
vector<vector<int> > levelOrderBottom(TreeNode* root)
{
vector<vector<int> > matrix;
vector<int> temp;
if (root == NULL)
{
return matrix;
}
queue<TreeNode *> tque;
tque.push(root);
//temp.push_back(root->val);
//matrix.push_back(temp);
TreeNode *p = NULL;
while (!tque.empty())
{
int levelSize = tque.size();
temp.clear();
for (int i = 0; i < levelSize; i++)
{
p = tque.front();
tque.pop();
if (p->left != NULL)
{
tque.push(p->left);
}
if (p->right != NULL)
{
tque.push(p->right);
}
temp.push_back(p->val);
}
matrix.push_back(temp);
}
int start = 0, end = matrix.size()-1;
while (start < end)
{
temp = matrix[start];
matrix[start] = matrix[end];
matrix[end] = temp;
start++; end--;
}
return matrix;
}
};
代码说明:
在实现代码中,采用STL模板中的队列来进行辅助计算,每一层循环都先读取队列长度,作为内存循环的次数,此即每层的个数。
需要注意的是,题目中要求结果为从上到下的顺序排序,而vector模板的push_back函数每次是将新元素添加至末尾,所以还需要进行一次对调工作。