二叉搜索树节点最小距离

智能指针迭代器

  1. use std::rc::Rc;
  2. use std::cell::RefCell;
  3. impl Solution {
  4. pub fn min_diff_in_bst(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
  5. fn tile(maybe_node: Option<Rc<RefCell<TreeNode>>>, nums: &mut Vec<i32>) {
  6. if let Some(node) = maybe_node {
  7. tile(node.borrow_mut().left.take(), nums);
  8. nums.push(node.borrow().val);
  9. tile(node.borrow_mut().right.take(), nums);
  10. }
  11. }
  12. let mut nums = Vec::new();
  13. tile(root, &mut nums);
  14. nums.windows(2).map(|x| x[1]-x[0]).min().unwrap_or(0)
  15. }
  16. }