题目: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).
思路:
由于题目要求输出结果中每一层的结点是分开的。所以需要再层序遍历的过程中加入一个标记,来区分当时是哪一层。所用的方法就是在根结点入队列之后就马上把一个NULL入队。当再次看到这个NULL的时候,说明该层结束了,这是马上再入一个NULL,表示新层的开始。当遇到NULL且此时队列已经为空的时候,说明所有节点遍历完毕。
代码:
/**
* Definition for binary tree
* 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> > v;
if(root == NULL)
return v;
vector<int> tmp;
queue<TreeNode *> q;
q.push(root);
q.push(NULL);
while(!q.empty())
{
TreeNode *k = q.front();
q.pop();
if(k == NULL)
{
if(!q.empty()) // 如果后面还有元素,就再一个NULL
q.push(NULL);
v.push_back(tmp);
tmp.clear();
continue;
}
tmp.push_back(k->val);
if(k->left != NULL)
q.push(k->left);
if(k->right != NULL)
q.push(k->right);
}
reverse(v.begin(), v.end());
return v;
}
};