zoukankan      html  css  js  c++  java
  • leetcode 663. 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

    比赛的时候,sb了,求每颗子树的和的时候开了个数组用 i+1 和i+2去做下标,真是2啊。说这些都没用....

    其实,这题很简单,记录每个子树的和,如果是总和的1/2那么就能分成两个相等的子树。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int>v;
        int sum;
        int dfs (TreeNode* root) {
            if (root == NULL) return 0;
            int ans = 0;
            ans += dfs(root->left);
            ans +=dfs(root->right);
            ans += root->val;
            v.push_back(ans);
            return ans;
        }
        bool checkEqualTree(TreeNode* root) {
            sum = dfs(root);
            if (v.size() == 1) return false;
            for (int i = 0; i < v.size(); ++i) {
                if (2*v[i] == sum) return true;
            }
            return false;
        }
    };
  • 相关阅读:
    美化滚动条
    js 格式转化
    vue 实现 前端生成随机验证码
    Vue.js CLI4 Vue.config.js标准配置
    在鼠标右键 新建 添加md文件
    节流和防抖
    关于IE 浏览器 GET 请求缓存问题
    VSCode 背景插件
    Java后台开发Tomcat添加https支持小程序开发过程
    InnoDB与MyISAM等存储引擎对比
  • 原文地址:https://www.cnblogs.com/pk28/p/7399555.html
Copyright © 2011-2022 走看看