leetcode简单题24 N.111 二叉树的最小深度 rust描述

rust 复制代码
// [3,9,20,null,null,15,7] 2
// [2,null,3,null,4,null,5,null,6] 5
use std::rc::Rc;
use std::cell::RefCell;
// 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
    }
  }
}
// dfs
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn min_depth_helper(node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
        match node {
            Some(node) => {
                let left_depth = min_depth_helper(&node.borrow().left);
                let right_depth = min_depth_helper(&node.borrow().right);
                if left_depth == 0 || right_depth == 0 {
                    return left_depth + right_depth + 1;
                }
                left_depth.min(right_depth) + 1
            }
            None => 0,
        }
    }

    min_depth_helper(&root)
}
use std::collections::VecDeque;
// bfs
pub fn min_depth2(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    if root.is_none() {
        return 0;
    }

    let mut queue = VecDeque::new();
    queue.push_back((root, 1));

    while let Some((node, depth)) = queue.pop_front() {
        if let Some(node) = node {
            let node = node.borrow();
            if node.left.is_none() && node.right.is_none() {
                return depth;
            }
            if node.left.is_some() {
                queue.push_back((node.left.clone(), depth + 1));
            }
            if node.right.is_some() {
                queue.push_back((node.right.clone(), depth + 1));
            }
        }
    }

    0
}
fn main() {}
相关推荐
luj_17686 小时前
残熵算法实时化三大瓶颈突破
c语言·开发语言·网络·经验分享·算法
mCell7 小时前
你以为短链接只是 Hash + 301/302?
后端·算法·架构
KaMeidebaby8 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
luj_17689 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
tmlx3I0819 小时前
高光谱拼接算法(六)RANSAC 误匹配剔除
人工智能·算法·机器学习
不相心 -w-9 小时前
基础-滑动窗口-(定长 | 不定长)
算法
醉城夜风~9 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
明理的信封10 小时前
AI 基础设施的“去 Python 化“:Rust 与 C# 的两条替代路径
人工智能·python·rust
ysa05103010 小时前
【板子】ST表
c++·笔记·算法·板子
CHHH_HHH10 小时前
【C++11】深入解析C++可变参数模板
开发语言·c++·算法·stl·c++11