Skip to main content
Back to problems
#110
Easy Algorithms

Balanced binary tree

Tree Depth-First Search Binary Tree
57.9% acceptance
Feb 27, 2026
12127
839
Given a binary tree, determine if it is height-balanced.

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 is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
    fn height(node: Option<Rc<RefCell<TreeNode>>>) -> i32 {
      match node {
        None => 0,
        Some(n) => {
          let n_borrow = n.borrow();
          let left_height = height(n_borrow.left.clone());
          if left_height == -1 {
            return -1;
          }
          let right_height = height(n_borrow.right.clone());
          if right_height == -1 {
            return -1;
          }
          if (left_height - right_height).abs() > 1 {
            return -1;
          }
          1 + left_height.max(right_height)
        }
      }
    }
    
    height(root) != -1
  }
}