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 / 7
Return its level order traversal as:
[ 3], [9,20], [15,7]]
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
Analyse:
1. Recursion:if the level does isn't exist, create it and then push corresponding value into it.
Runtime:4ms.
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> >result; -Traverse (Root,0, result); the returnresult; - } - voidTraverse (treenode* Root,intLevel, vector<vector<int> >&result) { - if(!root)return; + if(Level = = Result.size ())//The level does not exist and need to create it -Result.push_back (vector<int> ()); + AResult[level].push_back (root->val); atTraverse (Root->left, Level +1, result); -Traverse (Root->right, Level +1, result); - } -};
2. iteration:using queue to store nodes. When poping the first node, we need to add their children (child) to the queue. Then keep poping until the queue is empty.
Runtime:8ms.
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> >result; - if(!root)returnresult; the -queue<treenode* >Qu; - Qu.push (root); - while(!Qu.empty ()) { + intn =qu.size (); -vector<int> level;//Store the visited nodes in + while(n--){ Atreenode* temp = Qu.front ();//Pop The first node in the queue atLevel.push_back (temp->val); - Qu.pop (); - if(temp->left) Qu.push (temp->left);//Add it Children (child) - if(temp->right) Qu.push (temp->Right ); - } - result.push_back (level); in } - returnresult; to } +};
Binary Tree level Order traversal