LeetCode July Challenge - Day 2

Problem: LeetCode July Challenge - Day 2

Ideas

  1. Recursion with height.

Solution:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    vector<vector<int>> ans;

    void recursion(TreeNode* root, int h = 0){
        if(root == NULL) return;
        if(h >= ans.size())
            ans.push_back(vector<int>());
        ans[h].push_back(root->val);
        recursion(root->left, h+1);
        recursion(root->right, h+1);
    }
    public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        recursion(root);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};