自然的解法,一层一层的添加节点,再打印
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> res; vector<vector<int>> data; int level = 0; GetPrintFromTopToBottom(root,0,data); for(int i = 0;i<data.size();i++){ for(int j=0;j<data[i].size();j++){ res.push_back(data[i][j]); } } return res; } void GetPrintFromTopToBottom(TreeNode* root,int level,vector<vector<int>> &data) { if(root == NULL){ return; } if(data.size() <= level){ data.push_back({root->val}); }else{ data[level].push_back(root->val); } GetPrintFromTopToBottom(root->left,level+1,data); GetPrintFromTopToBottom(root->right,level+1,data); } };