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 as:
[ [3], [9,20], [15,7]]
/** * Definition for binary tree * 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>> result; if(root==nullptr) return result; vector<TreeNode*> v; v.push_back(root); int curr=0; int last=1; while(curr<v.size()){ vector<int> temp; last=v.size(); while(curr<last){ temp.push_back(v[curr]->val); if(v[curr]->left!=nullptr) v.push_back(v[curr]->left); if(v[curr]->right!=nullptr) v.push_back(v[curr]->right); ++curr;} result.push_back(temp);} return result; } };