/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> >ans;
if(root==NULL)
return ans;
vector<int> vec;
queue<TreeNode *>que;
que.push(root);
int count=1;//上一层的节点数
while(que.empty()==false)
{
vec.clear();
int nextCount=0;
for(int i=0;i<count;i++)
{
TreeNode *curNode=que.front();
que.pop();
vec.push_back(curNode->val);
if(curNode->left!=NULL)
{
que.push(curNode->left);
nextCount++;
}
if(curNode->right!=NULL)
{
que.push(curNode->right);
nextCount++;
}
}
count=nextCount;
ans.push_back(vec);
}
int sta=0,end=ans.size()-1;
while(sta<end)//逆转vector,以实现从底往上分层输出
{
vector<int> tmp=ans[sta];
ans[sta]=ans[end];
ans[end]=tmp;
sta++;
end--;
}
return ans;
}
};
【leetcode】Binary Tree Level Order Traversal II
最新推荐文章于 2024-02-12 01:19:39 发布