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


  • 0
    K

    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;
        vector<vector<int> > answer;
        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) {
                answer.push_back(a);
                current_max_level = level;
            }
            answer.at(level).push_back(_root->val);
    
            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) {
                return answer;
            } else {   
                // initialise blank coloums for matrix (2D vector) answer
                // this has to be done each time the level is increased
                current_max_level = 0;
                answer.push_back(a);
    
                // 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);
                return answer;
            }
        }
    };

  • 0
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take the question post itself as a reference.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.