class Solution { public: vector<vector<int> > res; int max=0; //max记录树的深度 void findt(TreeNode* p,int t){ //判断树的深度 if(p==NULL) return; findt(p->left,t+1); findt(p->right,t+1); if(t>max) max=t; return; } void insert(TreeNode* p,int h){ //每层的val按从左往右插入对应容器 if(p==NULL) return; res[h].push_back(p->val); //插入 insert(p->left,h+1); insert(p->right,h+1); return; } vector<vector<int> > Print(TreeNode* pRoot) { int h=0,t=1;//t用来先判断树的深度 findt(pRoot,t);//判断深度递归 res.resize(max); //有多少层就定义几个小容器 insert(pRoot,h);//递归插入 return res; } };