思想:
使用队的思想,将每一层的节点放入队列中,依次弹出,同时将其children放入队列。
c++
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 vector<Node*> children; 7 8 Node() {} 9 10 Node(int _val, vector<Node*> _children) { 11 val = _val; 12 children = _children; 13 } 14 }; 15 */ 16 class Solution { 17 private: 18 vector<vector<int> > res; 19 vector<int> small_res; 20 queue<Node*> que; 21 public: 22 vector<vector<int>> levelOrder(Node* root) { 23 if(!root) return res; 24 que.push(root); 25 while(!que.empty()){ 26 small_res.erase(small_res.begin(),small_res.end()); 27 int s=que.size(); 28 for(int i=0;i<s;i++){ 29 Node *temp=que.front(); 30 que.pop(); 31 small_res.push_back(temp->val); 32 if(!temp->children.empty()){ 33 for(Node* child: temp->children){ 34 que.push(child); 35 } 36 } 37 } 38 res.push_back(small_res); 39 } 40 41 return res; 42 } 43 };
或者:(做了一些小改动)
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 vector<Node*> children; 7 8 Node() {} 9 10 Node(int _val, vector<Node*> _children) { 11 val = _val; 12 children = _children; 13 } 14 }; 15 */ 16 class Solution { 17 public: 18 vector<vector<int>> levelOrder(Node* root) { 19 vector<int>v1; 20 vector<vector<int>>v2; 21 if(root==NULL) return v2; 22 queue<Node*>q; 23 q.push(root); 24 while(!q.empty()){ 25 int cnt=q.size(); 26 v1.clear(); 27 while(cnt--){ 28 Node *tmp=q.front(); 29 v1.push_back(tmp->val); 30 q.pop(); 31 for(int i=0;i<tmp->children.size();i++){ 32 q.push(tmp->children[i]); 33 } 34 } 35 v2.push_back(v1); 36 } 37 return v2; 38 } 39 };