Update 0530.二叉搜索树的最小绝对差.md

This commit is contained in:
fw_qaq
2022-12-17 23:22:24 +08:00
committed by GitHub
parent f06d81c233
commit 723286ddf8

View File

@ -547,31 +547,25 @@ impl Solution {
递归中解决 递归中解决
```rust ```rust
static mut PRE: Option<i32> = None;
static mut MIN: i32 = i32::MAX;
impl Solution { impl Solution {
pub fn get_minimum_difference(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { pub fn get_minimum_difference(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
unsafe { let mut pre = None;
PRE = None; let mut min = i32::MAX;
MIN = i32::MAX; Self::inorder(root, &mut pre, &mut min);
Self::inorder(root); min
MIN
}
} }
pub fn inorder(root: Option<Rc<RefCell<TreeNode>>>) { pub fn inorder(root: Option<Rc<RefCell<TreeNode>>>, pre: &mut Option<i32>, min: &mut i32) {
if root.is_none() { if root.is_none() {
return; return;
} }
let node = root.as_ref().unwrap().borrow(); let node = root.as_ref().unwrap().borrow();
Self::inorder(node.left.clone()); Self::inorder(node.left.clone(), pre, min);
unsafe { if let Some(pre) = pre {
if let Some(pre) = PRE { *min = (node.val - *pre).min(*min);
MIN = (node.val - pre).min(MIN).abs();
}
PRE = Some(node.val)
} }
Self::inorder(node.right.clone()); *pre = Some(node.val);
Self::inorder(node.right.clone(), pre, min);
} }
} }
``` ```