337. House Robber III

来源:互联网 发布:开票软件金税盘未响应 编辑:程序博客网 时间:2024/06/05 14:31

题目描述:

he 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 that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

题目要求我们求出一个二叉树不相邻元素的和的最大值。首先,对于一个节点。有取和不取两种选择,如果取,则它的两个儿子不能被取。如果不取,则两个儿子可取可不取。代码如下:
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {      vector<int> getMoney(TreeNode* node) {          vector<int> ret(2, 0);          if(!node) return ret;          vector<int> lRet = getMoney(node->left);          vector<int> rRet = getMoney(node->right);          ret[0] = lRet[1] + rRet[1] + node->val;          ret[1] = max(lRet[0], lRet[1]) + max(rRet[0], rRet[1]);          return ret;      }  public:      int rob(TreeNode* root) {          vector<int> ret = getMoney(root);          return max(ret[0], ret[1]);      }  };  


0 0