zoukankan      html  css  js  c++  java
  • LeetCode 663. Equal Tree Partition

    原题链接在这里:https://leetcode.com/problems/equal-tree-partition/

    题目:

    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   3
    
    Output: True
    Explanation: 
        5
       / 
      10
          
    Sum: 15
    
       10
      /  
     2    3
    
    Sum: 15

    Example 2:

    Input:     
        1
       / 
      2  10
        /  
       2   20
    
    Output: False
    Explanation: 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

    题解:

    Calculate sum of each subtree. Check if there is a subtree's sum is half of whole tree.

    Use a HashMap to maintain sum value of subtree and its frequency.

    Since there is edge case that sum == 0. sum/2 is also 0. Thus there must be more than one occurance of subtree having 0 sum.

    Time Complexity: O(n). GetSum() takes O(n).

    Space: O(n).

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public boolean checkEqualTree(TreeNode root) {
    12         if(root == null){
    13             return true;
    14         }
    15         
    16         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    17         int sum = getSum(root, hm);
    18         if(sum == 0){
    19             return hm.get(sum/2) > 1;
    20         }
    21         
    22         return sum%2==0 && hm.containsKey(sum/2);
    23     }
    24     
    25     private int getSum(TreeNode root, HashMap<Integer, Integer> hm){
    26         if(root == null){
    27             return 0;
    28         }
    29         
    30         int sum = getSum(root.left, hm) + root.val + getSum(root.right, hm);
    31         hm.put(sum, hm.getOrDefault(sum, 0)+1);
    32         return sum;
    33     }
    34 }
  • 相关阅读:
    C++ 模板实现约瑟夫环
    C++实现向文件输出对象并读取对象
    C++实现对本地文件加行号并输出到本地文件
    C++ vector动态容量变化
    C++纯虚函数应用实例
    华为2016研发工程师-删数字
    iOS-宫格拼图
    iOS-审核4.3入坑(已出坑)
    Mac-关闭Mac电脑启动声音(咚~)
    彻底完全卸载SQL Server 2005教程
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11007071.html
Copyright © 2011-2022 走看看