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? > Rea
Algorithm one: breadth-first traversal
Use the queue as a FIFO.
At the end of each layer, insert a null pointer as the layer terminator.
The actual execution time on the Leetcode is 11ms.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class solution {public:vector<vector<int>> Levelorder (treenode* root) {VECTOR<VECTOR<INT&G T > ans; if (!root) return ans; Queue<treenode *> Q; Q.push (root); Q.push (0); Ans.push_back (vector<int> ()); while (!q.empty ()) {root = Q.front (); Q.pop (); if (!root) {Ans.push_back (vector<int> ()); if (Q.empty ()) break; Q.push (0); } else {ans.back (). push_back (Root->val); if (root->left) Q.push (root->left); if (root->right) Q.push (root->right); }} ans.pop_back (); return ans; }};
Algorithm two, depth-first recursive traversal
On the Leetcode the time of the implementation is 13MS. 2ms slower than the algorithm above. But the code is a little bit simpler.
Class Solution {public: vector<vector<int>> levelorder (treenode* root) { vector<vector< Int> >ans; Helper (ans, root, 0); return ans; } void Helper (Vector<vector<int> > &ans, TreeNode *root, int level) { if (!root) return; if (level = = Ans.size ()) Ans.push_back (vector<int> ()); Ans[level].push_back (root->val); Helper (ans, root->left, level+1); Helper (ans, root->right, level+1); };
Binary Tree Level Order traversal--Leetcode