leetcode-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.

Example 1:
3
/
2 3

3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/
4 5
/
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.

本题是一道树形DP问题。
思路:
一颗二叉树可以返回两种结果,选取父节点的结果与未选取父节点的结果。
其中,选取了父节点,则左右孩子节点都不能被选取。即F0(root) = root->val + F1(root->left) + F1(root->right).
未选取父节点,则左右孩子节点可选可不选,视情况而定。
即F1(root) = max(F0(root->left),F1(root->left))+max(F0(root->right),F1(root->right)).
<!–more–>