Leetcode
This commit is contained in:
parent
d06e49bcd7
commit
7b8a1436c5
6 changed files with 256 additions and 0 deletions
6
balanced-binary-tree-110/Cargo.toml
Normal file
6
balanced-binary-tree-110/Cargo.toml
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "balanced-binary-tree-110"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
54
balanced-binary-tree-110/src/main.rs
Normal file
54
balanced-binary-tree-110/src/main.rs
Normal 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!");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue