题解 | #二叉搜索树最小差值# | Rust

二叉搜索树最小差值

https://www.nowcoder.com/practice/f8ac976b49bd450887b9281f315186c7

/**
 * #[derive(PartialEq, Eq, Debug, Clone)]
 * pub struct TreeNode {
 *     pub val: i32,
 *     pub left: Option<Box<TreeNode>>,
 *     pub right: Option<Box<TreeNode>>,
 * }
 *
 * impl TreeNode {
 *     #[inline]
 *     fn new(val: i32) -> Self {
 *         TreeNode {
 *             val: val,
 *             left: None,
 *             right: None,
 *         }
 *     }
 * }
 */
struct Solution{
}

impl Solution {
    fn new() -> Self {
        Solution{}
    }

    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
        * @param root TreeNode类 
        * @return int整型
    */
    pub fn minDifference(&self, root: Option<Box<TreeNode>>) -> i32 {
        let mut ans:i32 = i32::MAX;
        let mut pre:i32 = -1;
        Solution::midOrder(self, root, &mut pre, &mut ans);
        return ans;
    }

    fn midOrder(&self, node:Option<Box<TreeNode>>, pre:&mut i32, ans:&mut i32) {
        if node.is_none() {
            return;
        }
        let mut node = node;
        Solution::midOrder(self, node.as_mut().unwrap().left.take(), pre, ans);
        if *pre != -1 {
            *ans = std::cmp::min(*ans, (node.as_ref().unwrap().val - *pre).abs());
        }
        *pre = node.as_ref().unwrap().val;
        Solution::midOrder(self, node.as_mut().unwrap().right.take(), pre, ans);
    }
}

全部评论

相关推荐

喜欢走神的孤勇者练习时长两年半:爱华,信华,等华,黑华
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务