Leetcode 337. 打家劫舍 III


地址 https://leetcode-cn.com/problems/house-robber-iii/

class Solution {
public:
	
	void dfs(TreeNode* root,int dp[2]) {
		if (root == NULL) return;
		
		int dpl[2] = { 0 }; int dpr[2] = { 0 };
		dfs(root->left, dpl);
		dfs(root->right, dpr);

		dp[0] = max(dp[0], max(dpl[0], dpl[1]) + max(dpr[0], dpr[1]));
		dp[1] = max(dp[1], root->val + dpl[0] + dpr[0]);
	 
		return;
	}

	int rob(TreeNode* root) {
		if (root == NULL) return 0;
		int dpl[2] = { 0 }; int dpr[2] = { 0 };
		dfs(root->left,dpl);
		dfs(root->right, dpr);
		int ans = 0;
		
		ans = max(ans, root->val + dpl[0] + dpr[0]);
		ans = max(ans, max(dpl[0],dpl[1]) + max(dpr[0], dpr[1]));
		
		return ans;
	}
};

我的视频题解空间