动态规划-树形街区偷窃问题

2018-07-26  本文已影响0人  mrjunwang

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.

解题思路:假设树里有N个节点。定义一个函数f(n)为每个节点的最大抢劫量。
第一种情况,不抢父亲:f(root)=f(left)+f(right)//孩子和父亲不能同时抢。
第二种情况:抢父亲:此时需要定义一个新的函数g,表示不抢当前根节点的最大抢劫量,f(root)=root.value+g(root.left)+g(root.right).
g初始化:如果一个节点的左右孩子都为空,则g(n)=0;如果左右孩子有一个为空,且该孩子是叶子节点,则g就等于非空的孩子的节点值。如果左右都不为空,则g(root)=f(left)+f(right)
f初始化:如果节点root的左右孩子均为空,则返回节点root的值。如果左右孩子有一个为空,且该孩子是叶子节点,则返回节点root和左孩子或右孩子中较大的一个的值。

public int getMaxTreeValue(TreeNode<Integer> root) {
        if (root == null) {
            return 0;
        }
        int max1 = root.getValue() + getMaxChildValue(root.getLeft())
                + getMaxChildValue(root.getRight());
        int max2 = getMaxTreeValue(root.getLeft())
                + getMaxTreeValue(root.getRight());
        return Math.max(max1, max2);
    }

    /**
     * @param left
     * @return <p>
     *         Description:
     *         </p>
     */
    public  Integer getMaxChildValue(TreeNode<Integer> root) {
        if (root == null) {
            return 0;
        }
        return getMaxTreeValue(root.getLeft())+getMaxTreeValue(root.getRight());
    }
上一篇下一篇

猜你喜欢

热点阅读