Equal Tree Partition — LeetCode 663 Python Solution
MediumLeetCode PremiumTreeDepth-First SearchBinary Tree
- Problem
- #663
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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
- Input
- root = [5,10,10,null,null,2,3]
- Output
- true
Python solution
Python
# 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 seenComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 663. Equal Tree Partition is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 663. Equal Tree Partition?
- LeetCode 663. Equal Tree Partition is rated Medium on LeetCode.
- What is the time complexity of LeetCode 663. Equal Tree Partition?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 663. Equal Tree Partition?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 663. Equal Tree Partition cover?
- LeetCode 663. Equal Tree Partition is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
- Is LeetCode 663. Equal Tree Partition a premium problem?
- Yes. LeetCode 663. Equal Tree Partition is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.