@@ -63,7 +63,7 @@ https://leetcode-cn.com/problems/house-robber-iii/
6363
6464## 代码
6565
66- 语言支持:JS, Python
66+ 语言支持:JS, C++,Java, Python
6767
6868JavaScript Code:
6969
@@ -89,6 +89,78 @@ var rob = function (root) {
8989};
9090```
9191
92+ C++ Code:
93+ ``` c++
94+ /* *
95+ * Definition for a binary tree node.
96+ * struct TreeNode {
97+ * int val;
98+ * TreeNode *left;
99+ * TreeNode *right;
100+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
101+ * };
102+ */
103+ class Solution {
104+ public:
105+ int rob(TreeNode* root) {
106+ pair<int, int> res = dfs(root);
107+ return max(res.first, res.second);
108+ }
109+
110+ pair<int, int> dfs(TreeNode* root)
111+ {
112+ pair<int, int> res = {0, 0};
113+ if(root == NULL)
114+ {
115+ return res;
116+ }
117+
118+ pair<int , int > left = dfs(root->left);
119+ pair<int , int > right = dfs(root->right);
120+ // 0 代表不偷,1 代表偷
121+ res.first = max(left.first, left.second) + max(right.first, right.second);
122+ res.second = left.first + right.first + root->val;
123+ return res;
124+ }
125+
126+ };
127+ ```
128+
129+ Java Code:
130+ ``` java
131+ /**
132+ * Definition for a binary tree node.
133+ * public class TreeNode {
134+ * int val;
135+ * TreeNode left;
136+ * TreeNode right;
137+ * TreeNode(int x) { val = x; }
138+ * }
139+ */
140+ class Solution {
141+ public int rob (TreeNode root ) {
142+ int [] res = dfs(root);
143+ return Math . max(res[0 ], res[1 ]);
144+ }
145+
146+ public int [] dp (TreeNode root )
147+ {
148+ int [] res = new int [2 ];
149+ if (root == null )
150+ {
151+ return res;
152+ }
153+
154+ int [] left = dfs(root. left);
155+ int [] right = dfs(root. right);
156+ // 0 代表不偷,1 代表偷
157+ res[0 ] = Math . max(left[0 ], left[1 ]) + Math . max(right[0 ], right[1 ]);
158+ res[1 ] = left[0 ] + right[0 ] + root. val;
159+ return res;
160+ }
161+ }
162+ ```
163+
92164Python Code:
93165
94166``` python
0 commit comments