层次遍历:用栈来保存节点
但是涉及到按层输出的话 就需要两个queue队列,其中一个队列用来保存每一层的节点
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> res;
queue<TreeNode*> que;
if(root ==nullptr)return res;
que.push(root);
while(!que.empty()){
vector<int> tmp;
queue<TreeNode*> hie;
while(!que.empty()){
TreeNode* root = que.front();
que.pop();
tmp.push_back(root->val);
if(root->left!=nullptr)hie.push(root->left);
if(root->right!=nullptr)hie.push(root->right);
}
que = hie;
res.push_back(tmp);
}
return res;
}
};
?
|