Hierarchical traversal of binary tree
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 */Ten classSolution { One Public: Avector<vector<int>> Levelorder (treenode*root) { -vector<vector<int>>v; - if(!root)returnv; thevector<int>T; - -T.push_back (root->val); - V.push_back (t); +Root->val =1; - +Queue<treenode*>Q; A Q.push (root); at - while(!Q.empty ()) { -treenode* now =Q.front (); - Q.pop (); - if(!now)Continue; - inQ.push (now->Left ); -Q.push (now->Right ); to if(Now->val <v.size ()) { + if(now->left) V[now->val].push_back (now->left->val); - if(now->right) V[now->val].push_back (now->right->val); the } * Else{ $vector<int>T; Panax Notoginseng if(now->left) T.push_back (now->left->val); - if(now->right) T.push_back (now->right->val); the if(T.size ()! =0) V.push_back (t); + } A if(now->left) Now->left->val = Now->val +1; the if(now->right) Now->right->val = Now->val +1; + } - //Reverse (V.begin (), V.end ()); $ returnv; $ } -};
Leetcode 102 binary Tree level Order traversal two forks +bfs