方法同上一篇博客的方法类似
C++实现:
/**
* 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>> v;
void build(TreeNode* root, int depth){
if(root == NULL)
return;
while(v.size()<=depth){
v.push_back(vector<int>());
}
v[depth].push_back(root->val);
build(root->left, depth+1);
build(root->right, depth+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
build(root, 0);
return v;
}
};