问题描述:
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).
示例:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
问题分析:
要获取每一层的结点信息,首推树的层次遍历BFS。每遍历一层,就可以将它存储到数组中。
过程详见代码:
/**
* Definition for a binary tree node.
* 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) {
vector<vector<int> > res;
if(root == NULL) return res;
queue<TreeNode*> q,tq;
q.push(root);
tq.push(root);
while(!tq.empty())
{
vector<int> v;
while(!q.empty())
{
TreeNode* node = q.front();
v.push_back(node->val);
if(node->left != NULL)
tq.push(node->left);
if(node->right != NULL)
tq.push(node->right);
tq.pop();
q.pop();
}
res.insert(res.begin(),v);
q = tq;
}
return res;
}
};
代码不难理解~~~