# My accepted solution -- any suggestions on making it better?

• This is my accepted solution. Any suggestions or comments on making it better?

Thank you very much :)

``````struct TreeNodeWithLevel {
int val;
int level;
TreeNodeWithLevel *left;
TreeNodeWithLevel *right;
TreeNodeWithLevel(int x, int y) : val(x), level(y), left(NULL), right(NULL) {}
};

class Solution {
private:
vector<int> a;
int current_max_level;

public:

void createTreeNodeWithLevel(TreeNodeWithLevel *_root_with_level_ptr, TreeNode *_root, int level = 0) {

// copy value and add the level
_root_with_level_ptr->val = _root->val;
_root_with_level_ptr->level = level;

// give an extra column whenever required
if (level > current_max_level) {
current_max_level = level;
}

if (_root->left) {
// going left so increase the level and assign new treenode there
level = _root_with_level_ptr->level + 1;
_root_with_level_ptr->left = new TreeNodeWithLevel(0, level);

createTreeNodeWithLevel(_root_with_level_ptr->left, _root->left, level);
}

if (_root->right) {
// going right so increase the level and assign new treenode there
level = _root_with_level_ptr->level + 1;
_root_with_level_ptr->right = new TreeNodeWithLevel(0, level);

createTreeNodeWithLevel(_root_with_level_ptr->right, _root->right, level);
}
return;
}

vector<vector<int> > levelOrder(TreeNode *root) {

if (root == NULL) {
} else {
// initialise blank coloums for matrix (2D vector) answer
// this has to be done each time the level is increased
current_max_level = 0;

// make a new data structure
TreeNodeWithLevel root_with_level(root->val, 0);
TreeNodeWithLevel *root_with_level_ptr = &root_with_level;

createTreeNodeWithLevel(root_with_level_ptr, root);