House Robber III

题目

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

答案

class Solution {
    public int rob(TreeNode root) {
        if(root == null) return 0;
        return Math.max(robyes(root), robno(root));
    }
    
    public int robyes(TreeNode root) {
        if(root == null) return 0;
        int value = root.val;
        int rob_left_no = robno(root.left);
        int rob_right_no = robno(root.right);
        return value + rob_left_no + rob_right_no;
    }
    
    public int robno(TreeNode root) {
        if(root == null) return 0;
        return rob(root.left) + rob(root.right);
    }
    
}

下面这个答案很离奇的TLE了,大概跟recursion的结构有关

class Solution {
    public int rob(TreeNode root) {
        return Math.max(robhelp(root, true), robhelp(root, false));
    }
    
    public int robhelp(TreeNode root, boolean robbed) {
        if(root == null) return 0;
        int value = root.val;
        
        if(robbed) {
            int rob_left_no = robhelp(root.left, false);
            int rob_right_no = robhelp(root.right, false);
            return value + rob_left_no + rob_right_no;
        }
        else {
            int rob_left_yes = robhelp(root.left, true);
            int rob_right_yes = robhelp(root.right, true);
            int rob_left_no = robhelp(root.left, false);
            int rob_right_no = robhelp(root.right, false);
            return Math.max(rob_left_yes, rob_left_no) + Math.max(rob_right_yes, rob_right_no);
        }
    }
}

你可能感兴趣的:(House Robber III)