小编Ayl*_*lei的帖子

错误:实例化 `func::<[closure]>` 时达到递归限制

我正在尝试测试二叉搜索树是否有效:

use std::{cell::RefCell, rc::Rc};

pub struct TreeNode {
    val: i32,
    left: Option<Rc<RefCell<TreeNode>>>,
    right: Option<Rc<RefCell<TreeNode>>>,
}

pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
    preorder_traverse(root.as_ref(), |_| true)
}

fn preorder_traverse<F: Fn(i32) -> bool>(root: Option<&Rc<RefCell<TreeNode>>>, predict: F) -> bool {
    if let Some(node) = root {
        let root_val = root.as_ref().unwrap().borrow().val;
        if !predict(root_val) {
            return false;
        }
        preorder_traverse(node.borrow().left.as_ref(), |v| v < root_val)
            && preorder_traverse(node.borrow().right.as_ref(), |v| v > root_val)
    } else {
        true
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场):

此代码触发以下错误消息,这对我来说似乎毫无意义:

use std::{cell::RefCell, rc::Rc};

pub struct TreeNode …
Run Code Online (Sandbox Code Playgroud)

closures rust

9
推荐指数
1
解决办法
2553
查看次数

有没有办法使不可变引用变为可变?

我想解决Rust中的leetcode问题(从列表末尾删除第N个节点).我的解决方案使用两个指针来查找Node要删除的内容:

#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode { next: None, val }
    }
}

// two-pointer sliding window
impl Solution {
    pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
        let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head }));
        let mut start = dummy_head.as_ref();
        let mut end = dummy_head.as_ref();
        for _ in 0..n {
            end …
Run Code Online (Sandbox Code Playgroud)

mutability rust data-structures interior-mutability

1
推荐指数
2
解决办法
758
查看次数