337. House Robber III
2016-07-26 16:50
369 查看
题目:House Robber III
原题链接:https://leetcode.com/problems/house-robber-iii/The 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.
给出一个二叉树,求能够得到的最大节点和。
要求:节点不能直接相连。
采用深度优先遍历,统计左子树和右子树分别在加入对应根节点数值和不加入对应根节点数值的情况下的最大和,然后比较。
假设左子树加入根节点和不加入根节点计算的情况下的和分别为robRootL和noRobRootL,右子树在加入根节点和不加入根节点计算的情况下的和分别为,robRootR和noRobRootR。
那么当递归到根节点时:
加入根节点计算的情况下的最大和是:noRobRootL + noRobRootR + root->val
不加入根节点计算的情况下的最大和是:max(robRootL, noRobRootL) + max(robRootR, noRobRootR)
然后再比较两者,取最大值即可。
代码如下:
/** * 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: void DFS(TreeNode* root, int& robRoot, int& noRobRoot) { robRoot = 0, noRobRoot = 0; if(!root) return; int robL, robR, noRobL, noRobR; DFS(root->left, robL, noRobL); DFS(root->right, robR, noRobR); robRoot = noRobL + noRobR + root->val; noRobRoot = max(robL, noRobL) + max(robR, noRobR); return; } int rob(TreeNode* root) { int robRoot, noRobRoot; DFS(root, robRoot, noRobRoot); return max(robRoot, noRobRoot); } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解