LeetCode337.打家劫舍III

在这里插入图片描述
这道题我的思路是错的,没有写出来,看了别人的思路
在这里插入图片描述
用递归来写代码,但是效率不高

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   int max = 0;
    public int rob(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = rob(root.left);
        int right = rob(root.right);
        int leftleft = root.left == null? 0:rob(root.left.left)+rob(root.left.right);
        int rightright = root.right == null? 0:rob(root.right.left)+rob(root.right.right);
        return Math.max(left+right,leftleft+rightright+root.val);
    }
    
}
发布了169 篇原创文章 · 获赞 5 · 访问量 7711

猜你喜欢

转载自blog.csdn.net/fsdgfsf/article/details/104329126
今日推荐