[LeetCode]House Robber III

A slow one:

/**
 * 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 {  
public:  
    int rob(TreeNode* root) {
        if(root == NULL) {
            return 0;
        }

        if(root->left == NULL && root->right == NULL) {
            return root->val;
        }

        int leftMax = 0;
        int rightMax = 0;
        int leftleft = 0;
        int leftright = 0;
        int rightleft = 0;
        int rightright = 0;

        if(root->left != NULL) {
            leftMax = rob(root->left);
            leftleft = rob(root->left->left);
            leftright = rob(root->left->right);
        }

        if(root->right != NULL) {
            rightMax = rob(root->right);
            rightleft = rob(root->right->left);
            rightright = rob(root->right->right);
        }

        return max(leftMax + rightMax, root->val + leftleft + leftright + rightleft + rightright);
    }
};

It takes more than 1200 ms in the submission.Slowly.

If we save the results in a map,the time will be reduced to 59 ms.
An unordered_map will take only 33 ms.But I think there must be some faster ways.

/**
 * 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 {  
public:  
    int rob(TreeNode* root) {
        if(hm.find(root) != hm.end()) {
            return hm[root];
        } else {
            if(root == NULL) {
                hm[root] = 0;
                return 0;
            }

            if(root->left == NULL && root->right == NULL) {
                hm[root] = root->val;
                return root->val;
            }

            int leftMax = 0;
            int rightMax = 0;
            int leftleft = 0;
            int leftright = 0;
            int rightleft = 0;
            int rightright = 0;

            if(root->left != NULL) {
                leftMax = rob(root->left);
                leftleft = rob(root->left->left);
                leftright = rob(root->left->right);
            }

            if(root->right != NULL) {
                rightMax = rob(root->right);
                rightleft = rob(root->right->left);
                rightright = rob(root->right->right);
            }

            hm[root] = max(leftMax + rightMax, root->val + leftleft + leftright + rightleft + rightright);
            return hm[root];
        }
    }

private:  
    map<TreeNode*, int> hm;
};