題目描述
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},
return its bottom-up level order traversal as:
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
題目大意
實(shí)現(xiàn)二叉樹自底層向上層的層序遍歷蒸眠。
思路
還是二叉樹層序遍歷的問題狡相,只不過是自下向上捶朵;
很好解決
在C++中匈睁,可以用vector蹬碧,可以實(shí)現(xiàn)在vector前邊插入:
vector<vector<int > > vec; // 定義二維數(shù)組皇筛,其中元素為int類型
vector<int > vt; // 二維數(shù)組的新一行
vec.insert(vec.begin(), vt); // 在二維數(shù)組前面插入新的一行
或者在Java中:
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
res.add(0, list);·
也可以實(shí)現(xiàn)在二維數(shù)組前面插入一行。
但是經(jīng)過我在用C++的實(shí)驗(yàn)社痛,發(fā)現(xiàn)先用vec.push_back(vt)的方式见转,插入,然后最后的時候用swap(vec[i], vec[j])交換一下蒜哀,不管是空間還是時間斩箫,效率更優(yōu)。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
/*
結(jié)構(gòu)體定義
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
具體實(shí)現(xiàn)算法
*/
typedef TreeNode* tree;
vector<vector<int> > levelOrderBottom(TreeNode *root)
{
vector<vector<int > > vec; // 定義二維數(shù)組撵儿,其中元素為int類型
if(root == NULL)return vec;
queue<tree> qu; // 保存二叉樹層序遍歷結(jié)點(diǎn)的指針
qu.push(root); // 頭指針入隊(duì)
while(!qu.empty())
{
int index = qu.size(); // 本層的結(jié)點(diǎn)個數(shù)
vector<int > vt; // 二維數(shù)組的新一行
tree now; // 暫存當(dāng)前結(jié)點(diǎn)
while(index--)
{
now = qu.front(); // 暫存當(dāng)前結(jié)點(diǎn)
qu.pop(); // 出隊(duì)
vt.push_back(now->val);
if(now->left != NULL)qu.push(now->left); // 入隊(duì)
if(now->right != NULL)qu.push(now->right); // 入隊(duì)
}
// 如果vt不為空乘客,則加入到二維數(shù)組的新一行中
// 其實(shí)分析可以發(fā)現(xiàn),vt也不可能為空
if(vt.size())
vec.push_back(vt);
}
// 因?yàn)樽韵孪蛏系硇該Q一下
for(int i=0,j=vec.size()-1; i<j; i++,j--)
{
swap(vec[i], vec[j]);
}
return vec;
}
// 二叉樹的層序遍歷算法
void print(TreeNode *root)
{
queue<tree > qu;
qu.push(root);
while(!qu.empty())
{
tree now = qu.front();
qu.pop();
cout<<now->val<<endl;
if(now->left != NULL)qu.push(now->left);
if(now->right != NULL)qu.push(now->right);
}
}
int main()
{
tree tr;
tr = new TreeNode(1);
tree t1;
t1 = new TreeNode(2);
tr->left = t1;
tree t2;
t2 = new TreeNode(3);
tr->right = t2;
tree t3;
t3 = new TreeNode(4);
t2->left = t3;
vector<vector<int > > vec;
//print(tr);
vec = levelOrderBottom(tr);
for(int i=0; i<vec.size(); i++)
{
for(int j=0; j<vec[i].size(); j++)
{
cout<<vec[i][j]<<' ';
}
cout<<endl;
}
return 0;
}
以上易核。