#663
Medium Algorithms Equal tree partition
Tree Depth-First Search Binary Tree
42.3% acceptance
Mar 31, 2026
508
37
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.
Solution
Rust
Time O(n)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn check_equal_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
fn subtree_sum(node: &Option<Rc<RefCell<TreeNode>>>, sums: &mut Vec<i64>) -> i64 {
if let Some(n) = node {
let n = n.borrow();
let s = n.val as i64 + subtree_sum(&n.left, sums) + subtree_sum(&n.right, sums);
sums.push(s);
s
} else {
0
}
}
let mut sums = Vec::new();
let total = subtree_sum(&root, &mut sums);
// Remove the last element (root's sum = total), check if any subtree sum == total/2
sums.pop();
if total % 2 != 0 { return false; }
let half = total / 2;
sums.iter().any(|&s| s == half)
}
}