leetcode

来源:互联网 发布:淘宝尺寸文字自定义 编辑:程序博客网 时间:2024/05/17 20:22

题目

Given a binary tree with n nodes, your task is to check if it's possible to partition the tree to two trees which have the equal sum of values after removing exactly one edge on the original tree.

Example 1:

Input:         5   / \  10 10    /  \   2   3Output: TrueExplanation:     5   /   10      Sum: 15   10  /  \ 2    3Sum: 15

Example 2:

Input:         1   / \  2  10    /  \   2   20Output: FalseExplanation: You can't split the tree into two trees with equal sum after removing exactly one edge on the tree.

Note:

  1. The range of tree node value is in the range of [-100000, 100000].
  2. 1 <= n <= 10000

分析及解答

    public boolean checkEqualTree(TreeNode root) {        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        int sum = getsum(root, map);        if(sum == 0)return map.getOrDefault(sum, 0) > 1;        return sum%2 == 0 && map.containsKey(sum/2);    }        public int getsum(TreeNode root, Map<Integer, Integer> map ){        if(root == null)return 0;        int cur = root.val + getsum(root.left, map) + getsum(root.right, map);        map.put(cur, map.getOrDefault(cur,0) + 1);        return cur;    }