当前位置:   article > 正文

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

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


 

  1. // [3,9,20,null,null,15,7] 2
  2. // [2,null,3,null,4,null,5,null,6] 5
  3. use std::rc::Rc;
  4. use std::cell::RefCell;
  5. // Definition for a binary tree node.
  6. #[derive(Debug, PartialEq, Eq)]
  7. pub struct TreeNode {
  8. pub val: i32,
  9. pub left: Option<Rc<RefCell<TreeNode>>>,
  10. pub right: Option<Rc<RefCell<TreeNode>>>,
  11. }
  12. impl TreeNode {
  13. #[inline]
  14. pub fn new(val: i32) -> Self {
  15. TreeNode {
  16. val,
  17. left: None,
  18. right: None
  19. }
  20. }
  21. }
  22. // dfs
  23. pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
  24. fn min_depth_helper(node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
  25. match node {
  26. Some(node) => {
  27. let left_depth = min_depth_helper(&node.borrow().left);
  28. let right_depth = min_depth_helper(&node.borrow().right);
  29. if left_depth == 0 || right_depth == 0 {
  30. return left_depth + right_depth + 1;
  31. }
  32. left_depth.min(right_depth) + 1
  33. }
  34. None => 0,
  35. }
  36. }
  37. min_depth_helper(&root)
  38. }
  39. use std::collections::VecDeque;
  40. // bfs
  41. pub fn min_depth2(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
  42. if root.is_none() {
  43. return 0;
  44. }
  45. let mut queue = VecDeque::new();
  46. queue.push_back((root, 1));
  47. while let Some((node, depth)) = queue.pop_front() {
  48. if let Some(node) = node {
  49. let node = node.borrow();
  50. if node.left.is_none() && node.right.is_none() {
  51. return depth;
  52. }
  53. if node.left.is_some() {
  54. queue.push_back((node.left.clone(), depth + 1));
  55. }
  56. if node.right.is_some() {
  57. queue.push_back((node.right.clone(), depth + 1));
  58. }
  59. }
  60. }
  61. 0
  62. }
  63. fn main() {}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/847162
推荐阅读
相关标签
  

闽ICP备14008679号