c++ recursive solution easy to understand


  • 0
    Q
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        map<TreeNode*, int> mp;
    public:
        int findBottomLeftValue(TreeNode* root) {
            int res;
            if(!root->left && !root->right)
                return root->val;
            int l = get_height(root->left), r = get_height(root->right);
            if(l>=r)
                return findBottomLeftValue(root->left);
            else
                return findBottomLeftValue(root->right);
        }
        
        int get_height(TreeNode *root){
            if(root == nullptr)
                return 0;
            if(mp.find(root) != mp.end())
                return mp[root];
            mp[root] = 1 + max(get_height(root->left), get_height(root->right));
            return mp[root];
        }
    };
    

Log in to reply
 

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