Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 29, 2012 13:31
Show Gist options
  • Select an option

  • Save pdu/4406972 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4406972 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). http://www.leetcode.com/onlinejudge
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void bfs(vector< vector<int> >& ret, int& maxDepth, int curDepth, TreeNode* node) {
if (node == NULL) {
return;
}
if (curDepth > maxDepth) {
ret.resize(curDepth + 1);
maxDepth = curDepth;
}
ret[curDepth].push_back(node->val);
bfs(ret, maxDepth, curDepth + 1, node->left);
bfs(ret, maxDepth, curDepth + 1, node->right);
}
vector<vector<int> > levelOrder(TreeNode *root) {
vector< vector<int> > ret;
int maxDepth = -1;
bfs(ret, maxDepth, 0, root);
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment