动态规划_打家劫舍III

package 数据结构和算法;
public class d31_动态规划_打家劫舍III {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        
         TreeNode a= new TreeNode(3);
         TreeNode b= new TreeNode(4);
         TreeNode c= new TreeNode(5);
         TreeNode d= new TreeNode(1);
         TreeNode e= new TreeNode(3);
         TreeNode f= new TreeNode(0);
         TreeNode g= new TreeNode(1);
        
             
         a.setLeft(b);
         a.setRight(c);
         
         b.setLeft(d);
         b.setRight(e);
         
//             d.setLeft(f);
         c.setRight(g);
         
//             f.setLeft(h);
//             f.setRight(i);
           int res = rob3(a);
           System.out.print(res);
    }
    
    
    public static int rob3(TreeNode root) {
        int[] res = robAction1(root);
        return Math.max(res[0], res[1]);
    }


    private static int[] robAction1(TreeNode root) {
        // TODO 自动生成的方法存根
        int res[] = new int[2];
        if(root ==null) 
            return res;
        
        int[] left = robAction1(root.left);
        int[] right = robAction1(root.right);
        
        res[0]= Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        res[1] = root.val + left[0] + right[0];
        
        return res;
    }

 

posted @ 2022-12-11 13:48  依云科技  阅读(22)  评论(0)    收藏  举报