Simple Recursive Solution


  • 0
    U
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            
            vector<vector<int>> levelOrder; 
            
            if(root == nullptr)
                return levelOrder;
            
            auto treeHeight = getMaxDepth(root);
              
            for (auto i=1; i <= treeHeight; i++)
            {
                vector<int> nodesAtLevel;
                getNodesAtCurrentLevel(root,i, nodesAtLevel);
                levelOrder.push_back(nodesAtLevel);
            }
            
            return levelOrder;
        }
          
    private:
        void getNodesAtCurrentLevel(TreeNode* root, int level, vector<int>& result)
        {
            if(root == nullptr)
                return ;
            
            if(level == 1) {
                result.push_back(root->val);
                return;
            }
            
                getNodesAtCurrentLevel(root->left, level-1, result);
                getNodesAtCurrentLevel(root->right, level-1, result);
                        
        }
        
        int getMaxDepth(TreeNode* root)
        {
            if(root == nullptr)
                return 0;
            
            auto lHeight = getMaxDepth(root->left);
            auto rHeight = getMaxDepth(root->right);
            
            if(lHeight > rHeight) return lHeight + 1;
            else return rHeight + 1;
        }
    };
    

Log in to reply
 

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