House Robber III
2016-06-14 16:07
441 查看
c++
/** * 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 { public: int rob(TreeNode* root) { //left->right->root if (root == nullptr) return 0; int we_rob = 0, we_not_rob = 0; tryRob(root, we_rob, we_not_rob); return max(we_rob, we_not_rob); } private: void tryRob(const TreeNode* root, int& we_rob, int& we_not_rob) { if (root->left == nullptr && root->right == nullptr) { we_rob = root->val; we_not_rob = 0; return; } int cur_rob_left = 0; int cur_not_rob_left = 0; int cur_rob_right = 0; int cur_not_rob_right = 0; if(root->left) tryRob(root->left, cur_rob_left, cur_not_rob_left); if(root->right) tryRob(root->right, cur_rob_right, cur_not_rob_right); we_rob = cur_not_rob_left + cur_not_rob_right + root->val; int tmp1 = max(cur_rob_left + cur_rob_right, cur_not_rob_left + cur_not_rob_right); int tmp2 = max(cur_not_rob_left + cur_rob_right, cur_rob_left + cur_not_rob_right); we_not_rob = max(tmp1, tmp2); } };
python
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 we_rob, we_not_rob = self.tryRob(root) return max(we_rob, we_not_rob) def tryRob(self, root): if not root.left and not root.right: return root.val, 0 cur_rob_left, cur_not_rob_left = 0, 0 cur_rob_right, cur_not_rob_right = 0, 0 if root.left: cur_rob_left, cur_not_rob_left = self.tryRob(root.left) if root.right: cur_rob_right, cur_not_rob_right = self.tryRob(root.right) we_rob = cur_not_rob_left + cur_not_rob_right + root.val we_not_rob = max(cur_rob_left + cur_rob_right, cur_not_rob_left + cur_not_rob_right, cur_not_rob_left + cur_rob_right, cur_rob_left + cur_not_rob_right) return we_rob, we_not_rob
reference:
http://baike.baidu.com/view/1490835.htm
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- Lua和C语言的交互详解
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C语言自动生成enum值和名字映射代码
- C语言练习题:自由落体的小球简单实例
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中进制知识汇总
- C语言判断一个数是否是2的幂次方或4的幂次方
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构
- C语言实现选择排序、冒泡排序和快速排序的代码示例