https://leetcode.com/problems/binary-tree-level-order-traversal/
1.遞歸
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
bfs(root, 1);
return result;
}
vector<vector<int>> result;
void bfs(TreeNode* root, int depth){//用深度的編號來記錄層
if(root==nullptr) return ;
if( result.size() < depth){
vector<int> tmp;
result.push_back(tmp);
}
result[depth-1].push_back(root->val);
if(root->left != nullptr)
bfs(root->left, depth+1);//子節點深度加1
if(root->right!=nullptr)
bfs(root->right, depth+1);//子節點深度加1
}
};
2.非遞歸
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> a, b; //用兩個隊列交替存儲對方的子節點
if(root!=nullptr){
a.push(root);
}
while(!a.empty() || !b.empty()){
vector<int> tmp;
while(!a.empty()){
TreeNode* p = a.front();
a.pop();
tmp.push_back(p->val);
if(p->left!=nullptr)
b.push(p->left);
if(p->right!=nullptr)
b.push(p->right);
}
if(!tmp.empty())
result.push_back(tmp);
vector<int> second;
while(!b.empty()){
TreeNode* p = b.front();
b.pop();
second.push_back(p->val);
if(p->left!=nullptr)
a.push(p->left);
if(p->right!=nullptr)
a.push(p->right);
}
if(!second.empty())
result.push_back(second);
}
return result;
}
};