您的位置:首页 > 其它

[leetcode] Binary Tree Level Order Traversal II

2014-07-20 02:05 363 查看
Binary Tree Level
Order Traversal II

解法:上题基础上反序即可。

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<vector<int>> res;
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
if (root==NULL) {
return res;
}

queue<TreeNode*> curQ,nextQ;
curQ.push(root);

while (!curQ.empty()) {
vector<int> layerRes;

while (!curQ.empty()) {
TreeNode *tmp=curQ.front();
curQ.pop();
layerRes.push_back(tmp->val);

if (tmp->left!=NULL) {//使用!tmp->left出错
nextQ.push(tmp->left);
}
if (tmp->right!=NULL) {
nextQ.push(tmp->right);
}
}
curQ=nextQ;
while (!nextQ.empty()) {
nextQ.pop();
}
res.push_back(layerRes);
}

reverse(res.begin(), res.end());

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: