Skip to main content
Back to problems
#563
Easy Algorithms

Binary tree tilt

Tree Depth-First Search Binary Tree
65.4% acceptance
Jan 13, 2026
2372
2256
Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// 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 find_tilt(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    let mut total_tilt = 0;
    Self::dfs(&root, &mut total_tilt);
    total_tilt
  }

  fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, total: &mut i32) -> i32 {
    match node {
      None => 0,
      Some(n) => {
        let n = n.borrow();
        let left_sum = Self::dfs(&n.left, total);
        let right_sum = Self::dfs(&n.right, total);
        *total += (left_sum - right_sum).abs();
        left_sum + right_sum + n.val
      }
    }
  }
}