# Leetcode - Equal Tree Partition

violet posted @ May 21, 2020 06:35:19 AM in 算法 with tags Algorithm Golang DFS tree , 283 阅读

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
```

```/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func checkEqualTree(root *TreeNode) bool {
if root == nil {
return false
}
sumMap := map[int]int{}
total := sum(root, &sumMap)
if total % 2 != 0 {
return false
}
if total == 0 {
if sum(root.Right, &sumMap) != sum(root.Left, &sumMap) || root.Left == root.Right {
return false
}
return true
}
sumMap[total] = 0
if sumMap[total/2] == 1 {
return true
}
return false
}

func sum(root *TreeNode, sumMap *map[int]int) int {
if root == nil {
return 0
}
total := sum(root.Left, sumMap) + sum(root.Right, sumMap) + root.Val
(*sumMap)[total] = 1