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]]
Idea: Use a queue for storage, using two variables at the same time to record the number of nodes in that layer, and the number of nodes in the next layer.
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:vector<vector<int> > Levelorder (TreeNode *root) {vector<vector<int& gt;> result; if (root = NULL) return result; Queue<treenode *> LQ; Lq.push (root); int CURLC = 1; int NEXTLC = 0; while (!lq.empty ()) {vector<int> level; while (CURLC > 0) {TreeNode * temp = Lq.front (); Lq.pop (); curlc--; Level.push_back (Temp->val); if (temp->left) {Lq.push (temp->left); nextlc++; } if (temp->right) {Lq.push (temp->right); nextlc++; }} CURLC = NEXTLC; NEXTLC = 0; Result.push_back (level); } return result; }};
"Leetcode" Binary Tree level Order traversal