c++ solution using in order traversal (O(n))


  • 0
    int maxHeight(TreeNode* root) {
        return (root) ? max(maxHeight(root->left), maxHeight(root->right)) + 1 : 0;
    }
    void inOrder(TreeNode* root, int lvl, vector<vector<int>>& res) {
        if (!root) return;
        inOrder(root->left, lvl - 1, res);
        res[lvl].push_back(root->val);
        inOrder(root->right, lvl - 1, res);
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        int n = maxHeight(root);
        vector<vector<int>> res(n, vector<int>(0));
        inOrder(root, n - 1, res);
        return res;
    }
    

Log in to reply
 

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