题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
//c++递归的方法
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#include <cstddef>
#include <vector>
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
void recursionOrder(vector<vector<int>> &res,TreeNode* root,int depth){
if (root) {
if(res.size()<depth){
res.push_back(vector<int>{});
}
res[depth-1].push_back(root->val);
}else {
return;
}
recursionOrder(res, root->left, depth+1);
recursionOrder(res, root->right, depth+1);
}
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> res;
if(root==NULL){
return res;
}
recursionOrder(res,root,1);
return res;
}
};


