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.
即如何从树中选择几个节点,在确保这几个节点不直接相连的状况下使其值的和最大。面试
最开始的思路我是采用自顶向下递归遍历树的形式来计算可能得到的最大收益。当前节点的状况有两种:选中或是没选中,若是选中的话,那么两个直接子节点将不能够被选中,若是没选中,那么两个直接子节点的状态能够是选中或是没选中。代码以下:微信
public int rob(TreeNode root) { if(root == null) return 0; int result1 = root.val + (root.left == null ? 0 : rob(root.left.left) + rob(root.left.right)) + (root.right == null ? 0 : rob(root.right.left) + rob(root.right.right)); int result2 = rob(root.left) + rob(root.right); return Math.max(result1, result2); }
这段代码的缺陷在于,我须要遍历这棵树两次,分别为了获取选中当前节点和不选中当前节点的状况。而事实上咱们能够在一次遍历中就获得这两个状况对于当前节点的影响,并经过递归将值传递回上一层。很像是一种逆向思惟。ide
public int rob2(TreeNode root) { if (root == null) return 0; int[] value = robSum(root); return Math.max(value[0], value[1]); } private int[] robSum(TreeNode root) { int[] res = new int[2]; if (root == null) return res; int[] left = robSum(root.left); int[] right = robSum(root.right); res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); res[1] = root.val + left[0] + right[0]; return res; }
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~this