struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > result;
levelOrder(root, result);
return result;
}
void levelOrder(TreeNode *root, vector<vector<int> > &result) {
if (root == NULL) return;
queue<TreeNode *> nQueue;
nQueue.push(root);
nQueue.push(NULL);
result.push_back(vector<int>());
while(!nQueue.empty()) {
TreeNode *n = nQueue.front();
nQueue.pop();
if (n == NULL) {
if(!nQueue.empty()) {
nQueue.push(NULL);
result.push_back(vector<int>());
}
} else {
result[result.size()-1].push_back(n->val);
if(n->left != NULL) nQueue.push(n->left);
if(n->right != NULL) nQueue.push(n->right);
}
}
}
void preOrder(TreeNode *n, int level, vector<vector<int> > &result) {
if (n == NULL) return;
if (level >= result.size()) {
result.resize(level+1);
}
result[level].push_back(n->val);
preOrder(n->left, level+1, result);
preOrder(n->right, level+1, result);
}