0


leetcode简单题21 N.104 二叉树的最大深度 rust描述

// [3,9,20,null,null,15,7] 3
// [1,null,2] 2
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,
        }
    }
}
// 递归
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if let Some(node) = node {
            let left_depth = dfs(&node.borrow().left);
            let right_depth = dfs(&node.borrow().right);
            return 1 + left_depth.max(right_depth);
        }
        0
    }
    dfs(&root)
}
use std::collections::VecDeque;
// 迭代
pub fn max_depth2(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if root.is_none() {
            return 0;
        }

        let mut queue = VecDeque::new();
        queue.push_back(root);
        let mut depth = 0;

        while !queue.is_empty() {
            let level_size = queue.len();
            for _ in 0..level_size {
                if let Some(Some(node)) = queue.pop_front() {
                    let node = node.borrow();
                    if let Some(left) = node.left.clone() {
                        queue.push_back(Some(left));
                    }
                    if let Some(right) = node.right.clone() {
                        queue.push_back(Some(right));
                    }
                }
            }
            depth += 1;
        }
        depth
}

fn main() {
    // 根据 [3,9,20,null,null,15,7] 3 编写测试用例
    let root = Some(Rc::new(RefCell::new(TreeNode {
        val: 3,
        left: Some(Rc::new(RefCell::new(TreeNode::new(9)))),
        right: Some(Rc::new(RefCell::new(TreeNode {
            val: 20,
            left: Some(Rc::new(RefCell::new(TreeNode::new(15)))),
            right: Some(Rc::new(RefCell::new(TreeNode::new(7)))),
        }))),
    })));
    assert_eq!(max_depth(root.clone()), 3);
    assert_eq!(max_depth2(root.clone()), 3);
}
标签: leetcode rust 算法

本文转载自: https://blog.csdn.net/BECOMEviolet/article/details/140364812
版权归原作者 独好紫罗兰 所有, 如有侵权,请联系我们删除。

“leetcode简单题21 N.104 二叉树的最大深度 rust描述”的评论:

还没有评论