如何在Rust Option <rc <refcell <treenode >>>中进行递归树节点访问

时间:2019-05-19 11:19:03

标签: rust

我试图解决Leetcode问题。我在以下代码中收到错误:

// 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
//     }
//   }
// }
use std::cell::RefCell;
use std::rc::Rc;

impl Solution {
    pub fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, l: i32, r: i32) -> i32 {
        if let Some(t) = root {
            let t = t.borrow();

            if (t.val < l) {
                Solution::range_sum_bst(t.right, l, r)
            } else {
                if (t.val > r) {
                    Solution::range_sum_bst(t.left, l, r)
                } else {
                    t.val
                        + Solution::range_sum_bst(t.left, l, r)
                        + Solution::range_sum_bst(t.right, l, r)
                }
            }
        } else {
            0
        }
    }
}
Line 27: cannot move out of borrowed content in t.right in : Solution::range_sum_bst(t.right, l, r)

0 个答案:

没有答案