赞
踩
题目:
题解:
- struct SubtreeStatus {
- int selected;
- int notSelected;
- };
-
- struct SubtreeStatus dfs(struct TreeNode *node) {
- if (!node) {
- return (struct SubtreeStatus){0, 0};
- }
- struct SubtreeStatus l = dfs(node->left);
- struct SubtreeStatus r = dfs(node->right);
- int selected = node->val + l.notSelected + r.notSelected;
- int notSelected = fmax(l.selected, l.notSelected) + fmax(r.selected, r.notSelected);
- return (struct SubtreeStatus){selected, notSelected};
- }
-
- int rob(struct TreeNode *root) {
- struct SubtreeStatus rootStatus = dfs(root);
- return fmax(rootStatus.selected, rootStatus.notSelected);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。