二叉树的前中后序遍历--对应图中的深度优先---递归/迭代->栈
二叉树的层序遍历--对应图中的广度优先---迭代->队列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
vector<int> vec;
queue<TreeNode*> que;
if (root) que.push(root);
while (!que.empty()){
int size = que.size();
while (size--){
TreeNode* cur = que.front();
que.pop();
vec.push_back(cur->val);
if (cur->left) que.push(cur->left);
if (cur->right) que.push(cur->right);
}
result.push_back(vec);
vec.clear();
}
return result;
}
};