Given a binary tree, return the level order traversal of its nodes 'values. (ie, from left to right, level by level ).
For example:
Given Binary Tree{3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
Return its level order traversal:
[ [3], [9,20], [15,7]]
Confused what"{1,#,2,3}"
Means?
Struct treenode {int val; treenode * left; treenode * right; treenode (int x): Val (x), left (null), right (null ){}}; class solution {public: STD: vector <int> levelorder (treenode * root) {// The first solution uses the queue BFs to traverse the binary tree layer STD :: vector <STD: vector <int> VEC; If (root = NULL) return VEC; STD: queue <treenode *> q; q. push (Root); int CNT = 1; STD: vector <int> TMP; while (! Q. empty () {TMP. clear (); int level = 0; For (INT I = 0; I <CNT; I ++) {root = Q. front (); q. pop (); TMP. push_back (root-> Val); If (root-> left! = NULL) Q. Push (root-> left), Level ++; If (root-> right! = NULL) Q. Push (root-> right), Level ++;} CNT = level; Vec. push_back (TMP) ;}return VEC ;}};
Class solution {public: STD: vector <int> levelorder (treenode * root) {// The second method uses the queue method. However, in fact, the implementation of the data structure is vector. I think this method is easier. STD: vector <int> result; If (root = NULL) return result; STD: vector <int> VEC; STD :: vector <treenode *> node; node. push_back (Root); int cur = 0, last = 1; while (cur <node. size () {last = node. size (); While (cur <last) {Vec. push_back (node [cur]-> Val); If (node [cur]-> L EFT! = NULL) node. push_back (node [cur]-> left); If (node [cur]-> right! = NULL) node. push_back (node [cur]-> right); cur ++;} result. push_back (VEC); Vec. clear () ;}return result ;}};
Class solution {public: STD: vector <int> levelorder (treenode * root) {// The third solution is to traverse the binary tree DFS (root, 0); return result;} PRIVATE: STD: vector <int> result; void DFS (treenode * root, int level) {If (root = NULL) return; If (Level = result. size () {STD: vector <int> VEC; result. push_back (VEC);} result [level]. push_back (root-> Val); DFS (root-> left, level + 1); DFS (root-> right, level + 1 );}};
Leetcode-binary tree level order traversal