Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created March 1, 2013 20:49
Show Gist options
  • Save zhoutuo/5067681 to your computer and use it in GitHub Desktop.
Save zhoutuo/5067681 to your computer and use it in GitHub Desktop.
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
cal(res, 0, root);
return res;
}
void cal(vector<vector<int> >& res, int curLevel, TreeNode* node) {
if(node == NULL) {
return;
}
if(res.size() < curLevel + 1) {
res.push_back(vector<int>());
}
res[curLevel].push_back(node->val);
cal(res, curLevel + 1, node->left);
cal(res, curLevel + 1, node->right);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment