題目鏈接: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);
}
};