题目链接:click~
解法1:
/*题意:将二叉树中的结点一层一层的输出*/
/**
*思路:用两个队列,一个队列保存当前层的结点,另一队列保存下一层的结点。
* 当遍历某层结点时,插入下一层的结点。
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<int> v;
vector<vector<int>> path;
if(root == NULL) return path;
queue<TreeNode *> curr;
curr.push(root);
while(!curr.empty()) {
queue<TreeNode *> next;//下一层结点
while(!curr.empty()) {
TreeNode *p = curr.front();
v.push_back(p->val);
curr.pop();
//将下一层结点插入
if(p->left != NULL) next.push(p->left);
if(p->right != NULL) next.push(p->right);
}
curr = next;
path.push_back(v);
v.clear();
}
return path;
}
};
解法2:
class Solution {
public:
void DFS(TreeNode *T, int level, vector<vector<int>> &path) {
if(T == NULL) return;
if(level == path.size()) {
path.resize(level+1);
}
path[level].push_back(T->val);
DFS(T->left, level+1, path);
DFS(T->right, level+1, path);
}
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>> path;
if(root == NULL) return path;
DFS(root, 0, path);
}
};