赞
踩
一个二叉树,每个节点上都有权值,当父节点和子节点不能同时选中的前提下,二叉树的最大值
实例请看 :https://leetcode-cn.com/problems/house-robber-iii/
child_left_max = max(left_child_select,left_child_no_select)
child_right_max = max(right_child_select,right_child_no_select)
parent = max(child_left_max,child_right_max)
附上代码:
public int rob(TreeNode root) { if(root == null){ return 0; } // 定义一个HashMap 存储每个节点 盗窃的最优解 Map<TreeNode,Integer> result = new HashMap<>(); // 定义一个HashMap 储存每个节点 不盗窃的最优解 Map<TreeNode,Integer> result1 = new HashMap<>(); Stack<TreeNode> stack = new Stack<>(); Stack<TreeNode> stack1 = new Stack<>(); stack.add(root); stack1.add(root); while(!stack.isEmpty()){ TreeNode pop = stack.pop(); if(pop.left != null){ stack.add(pop.left); stack1.add(pop.left); } if(pop.right != null){ stack.add(pop.right); stack1.add(pop.right); } } while(!stack1.isEmpty()){ TreeNode pop = stack1.pop(); // 当 当前节点盗窃的情况下,最优解 // 当前节点盗窃 所以子节点都只能不盗窃 所以 左右节点的不盗窃最优解加上当前节点的值, result.put(pop,(pop.left == null ? 0:result1.get(pop.left)) + (pop.right == null ? 0:result1.get(pop.right)) + pop.val); // 当 当前节点不盗窃下的最优解 // 左右的节点都可以是盗窃和不盗窃 int leftMax = 0; if(pop.left != null){ leftMax = Math.max(result.get(pop.left),result1.get(pop.left)); } int rightMax = 0; if(pop.right != null){ rightMax = Math.max(result.get(pop.right),result1.get(pop.right)); } result1.put(pop,leftMax + rightMax); } return Math.max(result.get(root),result1.get(root)); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。