给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
解法一:
/**
* 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)
{
if(!root) return {};
queue<TreeNode *> qu;
qu.push(root);
vector<vector<int>> res;
while(!qu.empty())
{
vector<int> temp;
int n = qu.size();
while(n--)
{
TreeNode * s = qu.front();
qu.pop();
temp.push_back(s->val);
if(s->left) qu.push(s->left);
if (s->right) qu.push(s->right);
}
res.insert(res.begin(), temp);
}
return res;
}
};
解法二:
/**
* 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>> result;
vector<int> temp;
queue<TreeNode*> TreeQueue;
stack<vector<int>> TreeStack;
unsigned long cursize = 0;
if (root == NULL)
{
return result;
}
TreeQueue.push(root);
while (TreeQueue.size() != 0)
{
cursize = TreeQueue.size();
for (unsigned int index = 0; index < cursize; index++)
{
TreeNode* indexnode = TreeQueue.front();
TreeQueue.pop();
temp.push_back(indexnode->val);
if (indexnode->left != NULL)
{
TreeQueue.push(indexnode->left);
}
if (indexnode->right != NULL)
{
TreeQueue.push(indexnode->right);
}
}
TreeStack.push(temp);
temp.clear();
}
while (TreeStack.empty() != true)
{
result.push_back(TreeStack.top());
TreeStack.pop();
}
return result;
}
};