【问题标题】:How to create a recursive function that populate a common collection如何创建填充公共集合的递归函数
【发布时间】:2022-11-10 01:03:27
【问题描述】:

我需要创建一个简单的递归函数,以便以平衡的方式填充树。

该算法可以在这里找到:https://www.baeldung.com/cs/balanced-bst-from-sorted-list

我无法理解如何使用 Rust 共同拥有一个集合(树)。

谢谢 <3

【问题讨论】:

    标签: recursion rust binary-search-tree rust-cargo


    【解决方案1】:

    我认为这可能会解决您的问题。

    https://medium.com/go-rust/rust-day-12-balanced-binary-tree-c1f608803d94

    use std::rc::Rc;
    use std::cell::RefCell;
    impl Solution {
        pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
            match root {
                None => true,
                Some(curr_node) =>{
                    let curr_node = curr_node.borrow();
                    
                    let left  = Self::height(curr_node.left.clone());
                    let right = Self::height(curr_node.right.clone());
                    let diff  = i32::abs(left-right);
                    
                    if(diff <= 1){
                        return Self::is_balanced(curr_node.left.clone()) && Self::is_balanced(curr_node.right.clone());
                    }
                    
                    return false;
                }
            }
        }
        
        pub fn height(root: Option<Rc<RefCell<TreeNode>>>) -> i32{
            match root {
                None => 0,
                Some(curr_node) => {
                    let curr_node = curr_node.borrow();
                    1 + std::cmp::max( Self::height(curr_node.left.clone()), Self::height(curr_node.right.clone()) )
                }
            }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      相关资源
      最近更新 更多