/** * 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>> res; vector<vector<int>> levelOrder(TreeNode* root) { if(root==NULL) { return res; } DFS(1,root); return res; /* queue<TreeNode*> q; vector<vector<int>> res; if(root==NULL) { return res; } q.push(root); while(!q.empty()) { //当前存在于队列中的都是该层的 int curlength=q.size(); vector<int> temp; for(int i=0;i<curlength;i++) { TreeNode* node=q.front(); q.pop(); temp.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } res.push_back(temp); } return res; */ } //思路大致为 从root开始,进入第一层房间,然后root安顿好后,把孩子们往下一层安顿 void DFS(int index,TreeNode* root) { if(root==NULL) { return; } //还没有容纳当前层的房子,就新建一个 if(res.size()<index) { vector<int> temp; res.push_back(temp); } res[index-1].push_back(root->val); if(root->left) { DFS(index+1,root->left); } if(root->right) { DFS(index+1,root->right); } } };