
暴力递归(超时)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */class Solution { public int rob(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return root.val; //偷父节点 int val1 = root.val; if(root.left != null) { val1 += rob(root.left.left) + rob(root.left.right); } if(root.right != null) { val1 += rob(root.right.left) + rob(root.right.right); } //不偷父节点 int val2 = rob(root.left) + rob(root.right); return Math.max(val1,val2); }}
记忆化
class Solution { Map<TreeNode, Integer> map = new HashMap<>(); public int rob(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return root.val; if(map.containsKey(root) ) { return map.get(root); } //偷父节点 int val1 = root.val; if(root.left != null) { val1 += rob(root.left.left) + rob(root.left.right); } if(root.right != null) { val1 += rob(root.right.left) + rob(root.right.right); } //不偷父节点 int val2 = rob(root.left) + rob(root.right); map.put(root,Math.max(val1,val2) ); return Math.max(val1,val2); }}
动态规划
class Solution { public int rob(TreeNode root) { //dp[0]表示不偷该节点 //dp[1]表示偷该节点 int [] dp = myRob(root); return Math.max(dp[0],dp[1]); } public int [] myRob(TreeNode root ) { int [] dp = new int [2]; if(null == root ) { return dp; //初始化为{0,0} } int [] left = myRob(root.left); int [] right = myRob(root.right ); //不偷当前节点,取左右子节点最大值 加和 dp[0] = Math.max(left[0],left[1]) + Math.max(right[0],right[1]) ; dp[1] = root.val + left[0] + right[0]; return dp; }}