leetcode337

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int Rob(TreeNode root)
        {
            int[] num = dfs(root);
            return Math.Max(num[0], num[1]);
        }

        private int[] dfs(TreeNode x)
        {
            if (x == null) return new int[2];
            int[] left = dfs(x.left);
            int[] right = dfs(x.right);
            int[] res = new int[2];
            res[0] = left[1] + right[1] + x.val;
            res[1] = Math.Max(left[0], left[1]) + Math.Max(right[0], right[1]);
            return res;
        }
}

https://leetcode.com/problems/house-robber-iii/#/description

时间: 2024-07-29 06:40:25

leetcode337的相关文章

基于二叉树的抢劫问题 leetcode337

1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 class Solution { 12 public: 13 int rob(TreeNode* root)

LeetCode 337

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 t