0
点赞
收藏
分享

微信扫一扫

Binary Tree Level Order Traversal II 从下向上按层遍历二叉树


Binary Tree Level Order Traversal II


Given a binary tree, return the bottom-up level order

For example:

Given binary tree ​​{3,9,20,#,#,15,7}​​,


3 / \ 9 20 / \ 15 7



return its bottom-up level order traversal as:



[ [15,7], [9,20], [3] ]


confused what ​​"{1,#,2,3}"​​ means? ​​​> read more on how binary tree is serialized on OJ.​​

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > vec;
queue<TreeNode *> cur;
if(root==NULL)
return vec;

cur.push(root);

vector<int> vv;
queue<TreeNode *> next;

while(!cur.empty())
{
TreeNode *t = cur.front();
cur.pop();
vv.push_back(t->val);

if(t->left)
next.push(t->left);
if(t->right)
next.push(t->right);

if(cur.empty())
{
vec.insert(vec.begin(),vv);//vv从头插入
// cur=next;
//next.clear();
swap(cur,next);
vv.clear();
}
}

return vec;

}
};

举报

相关推荐

0 条评论