This commit is contained in:
Håkon Størdal 2025-05-02 19:22:31 +02:00
parent d06e49bcd7
commit 7b8a1436c5
6 changed files with 256 additions and 0 deletions

View file

@ -0,0 +1,6 @@
[package]
name = "balanced-binary-tree-110"
version = "0.1.0"
edition = "2024"
[dependencies]

View file

@ -0,0 +1,54 @@
// Definition for a binary tree node.
struct Solution {}
#[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::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
return check_height(root).is_ok();
fn check_height(root: Option<Rc<RefCell<TreeNode>>>) -> Result<i32, ()> {
if root.is_none() {
return Ok(0);
}
let node = root.unwrap();
let node_ref = node.borrow();
// Recursively check left subtree
let left_height = check_height(node_ref.left.clone())?;
// Recursively check right subtree
let right_height = check_height(node_ref.right.clone())?;
// Check if the current node is balanced
if (left_height - right_height).abs() > 1 {
return Err(());
}
// Return the height of the current subtree
Ok(1 + left_height.max(right_height))
}
}
}
fn main() {
println!("Hello, world!");
}