LeetCode 0663. Equal Tree Partition Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0663. Equal Tree Partition

Description

Given the root of a binary tree, return true if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree.

 

Example 1:

Input: root = [5,10,10,null,null,2,3]
Output: true

Example 2:

Input: root = [1,2,10,null,null,2,20]
Output: false
Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105

Solutions

Solution 1

PythonJavaC++Go
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def checkEqualTree(self, root: TreeNode) -> bool: def sum(root): if root is None: return 0 l, r = sum(root.left), sum(root.right) seen.append(l + r + root.val) return seen[-1] seen = [] s = sum(root) if s % 2 == 1: return False seen.pop() return s // 2 in seen(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !