智慧屏 安装 app如何提升家庭娱乐与教育体验的关键工具
1094
2022-08-23
[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小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~