博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
663. Equal Tree Partition
阅读量:6306 次
发布时间:2019-06-22

本文共 1198 字,大约阅读时间需要 3 分钟。

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.

 

 

/** * 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:    bool checkEqualTree(TreeNode* root) {         int sum = computeTreeSum(root);         if(sum==0) return cnts[0]>1;         return sum%2==0&&cnts[sum/2]>0?true:false;    }private:    int computeTreeSum(TreeNode *root)    {        if(!root) return 0;        int sum = root->val+computeTreeSum(root->left)+computeTreeSum(root->right);        cnts[sum]++;        return sum;    }    unordered_map
cnts;};

 

转载于:https://www.cnblogs.com/jxr041100/p/7889160.html

你可能感兴趣的文章
Git笔记
查看>>
普通人如何从平庸到优秀,在到卓越
查看>>
SLAM数据集
查看>>
c#学习笔记05——数组&集合
查看>>
【图论算法】Dijstra&BFS
查看>>
注册和上传文件(头像)
查看>>
使用OVS
查看>>
键盘回收的几种方法
查看>>
Python(条件判断和循环)
查看>>
day4 linux安装python
查看>>
LeetCode Container With Most Water (Two Pointers)
查看>>
vue (v-if show 问题)
查看>>
https基础
查看>>
css3 canvas之刮刮卡效果
查看>>
并查集模板
查看>>
RESTful Mongodb
查看>>
BZOJ3237:[AHOI2013]连通图(线段树分治,并查集)
查看>>
如何提高Ajax性能
查看>>
Android--自定义加载框
查看>>
LINUX下 lamp安装及配置
查看>>