高级农民
- 积分
- 2313
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-8-24
- 最后登录
- 1970-1-1
|
- public class CalcTree {
- static class TreeNode {
- String val;
- TreeNode left;
- TreeNode right;
- public TreeNode(String val) {
- this.val = val;
- this.left = null;
- this.right = null;
- }
- }
- TreeNode root;
- int sum;
- int deepestDepth;
- int minNumOfNodesToRemove;
- public CalcTree(TreeNode root) {
- this.root = root;
- this.minNumOfNodesToRemove = Integer.MAX_VALUE;
- }
- public int cal() {
- int res = helper(root);
- this.sum = res;
- return res;
- }
- public int helper(TreeNode root) {
- if (root.left == null && root.right == null) {
- return Integer.parseInt(root.val);
- }
- int leftVal = helper(root.left);
- int rightVal = helper(root.right);
- if ("+".equals(root.val)) {
- return leftVal + rightVal;
- } else {
- return leftVal - rightVal;
- }
- }
-
- public int minRemoveToGet(int target) {
- minNumOfNodesToRemove = Integer.MAX_VALUE;
- helper2(root, target, 0);
- return minNumOfNodesToRemove == Integer.MAX_VALUE ? -1 : minNumOfNodesToRemove;
- }
- private int helper2(TreeNode node, int target, int depth) {
- if (node.left == null && node.right == null) {
- // Based on the description we know it is a full binary tree. So total node number is 2 ^ (deepestDepth + 1) - 1.
- deepestDepth = depth;
- return Integer.parseInt(node.val);
- }
- int leftVal = helper2(node.left, target, depth + 1);
- int rightVal = helper2(node.right, target, depth + 1);
- int res = "+".equals(node.val) ? leftVal + rightVal : leftVal - rightVal;
- if (res == target) {
- int height = deepestDepth - depth + 1;
- int totalNumOfNodes = (int) (Math.pow(2, deepestDepth + 1) - 1);
- int curNumOfNodes = (int) (Math.pow(2, height) - 1);
- minNumOfNodesToRemove = Math.min(minNumOfNodesToRemove, totalNumOfNodes - curNumOfNodes);
- }
- return res;
- }
- public static void main(String[] args) {
- /**
- * +
- * + -
- * 6 5 4 3
- */
- TreeNode node1 = new TreeNode("+");
- TreeNode node2 = new TreeNode("+");
- TreeNode node3 = new TreeNode("-");
- node1.left = node2;
- node1.right = node3;
- TreeNode node4 = new TreeNode("6");
- TreeNode node5 = new TreeNode("5");
- TreeNode node6 = new TreeNode("4");
- TreeNode node7 = new TreeNode("3");
- node2.left = node4;
- node2.right = node5;
- node3.left = node6;
- node3.right = node7;
- CalcTree solution = new CalcTree(node1);
- System.out.println(solution.cal());
-
- System.out.println(solution.minRemoveToGet(11));
- System.out.println(solution.minRemoveToGet(1));
- System.out.println(solution.minRemoveToGet(13));
- }
- }
复制代码 |
|