给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
按照从下往上的层次遍历为:
[ [15,7], [9,20], [3] ]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: A tree
* @return: buttom-up level order a list of lists of integer
*/
vector<vector<int>> levelOrderBottom(TreeNode * root) {
// write your code here
vector<vector<int>> levels;
if (root == NULL) {
return levels;
}
queue<TreeNode*> qu;
stack<vector<TreeNode*>> st;
// root node
qu.push(root);
int count = 1;
while (count > 0) {
vector<TreeNode*> nodes;
while (count-- > 0) {
TreeNode* tn = qu.front();
qu.pop();
nodes.push_back(tn);
if (tn->left != NULL) {
qu.push(tn->left);
}
if (tn->right != NULL) {
qu.push(tn->right);
}
}
st.push(nodes);
count = qu.size();
}
while (!st.empty()) {
vector<TreeNode*> nodes = st.top();
st.pop();
vector<int> level;
for (int i = 0; i < nodes.size(); i++) {
level.push_back(nodes[i]->val);
}
levels.push_back(level);
}
return levels;
}
};