[leetcode] 530. Minimum Absolute Difference in BST

网友投稿 1094 2022-08-23

[leetcode] 530. Minimum Absolute Difference in BST

[leetcode] 530. Minimum Absolute Difference in BST

Description

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input: 1 \ 3 / 2Output:1Explanation:The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

Note: There are at least two nodes in this BST.

分析

题目的意思是:求出两个结点的最小绝对值。

中序遍历,左中右。

代码

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int getMinimumDifference(TreeNode* root) { int res=INT_MAX; int pre=-1; solve(root,pre,res); return res; } void solve(TreeNode* root,int& pre,int& res){ if(!root){ return; } solve(root->left,pre,res); if(pre!=-1) res=min(res,root->val-pre); pre=root->val; solve(root->right,pre,res); }};

参考文献

​​[LeetCode] Minimum Absolute Difference in BST 二叉搜索树的最小绝对差​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:redis 常用命令(redis持久化方式有几种)
下一篇:[leetcode] 385. Mini Parser
相关文章

 发表评论

暂时没有评论,来抢沙发吧~