二叉树的层次遍历
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode* root) { 13 vector<vector<int>> v; 14 if(!root) return v; 15 vector<int> t; 16 17 t.push_back(root->val); 18 v.push_back(t); 19 root->val = 1; 20 21 queue<TreeNode*> q; 22 q.push(root); 23 24 while(!q.empty()){ 25 TreeNode* now = q.front(); 26 q.pop(); 27 if(!now) continue; 28 29 q.push(now->left); 30 q.push(now->right); 31 if(now->val < v.size()){ 32 if(now->left) v[now->val].push_back(now->left->val); 33 if(now->right) v[now->val].push_back(now->right->val); 34 } 35 else{ 36 vector<int> t; 37 if(now->left) t.push_back(now->left->val); 38 if(now->right) t.push_back(now->right->val); 39 if(t.size() != 0)v.push_back(t); 40 } 41 if(now->left) now->left->val = now->val + 1; 42 if(now->right)now->right->val = now->val + 1; 43 } 44 //reverse(v.begin(),v.end()); 45 return v; 46 } 47 };
时间: 2024-10-31 16:35:24