530. Minimum Absolute Difference in BST
程序员文章站
2022-03-07 18:26:07
...
Problem
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example
Solution
BST中差值绝对值最小,只能出现在相邻节点。
本题与501题是类似的。
/**
* 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 ret = INT_MAX;
TreeNode* pre = NULL;
inOrder(root,pre,ret);
return ret;
}
void inOrder(TreeNode* root,TreeNode* &pre,int &ret)
{
if(!root)
return;
inOrder(root->left,pre,ret);
if(pre)
{
int curAD = abs(root->val - pre->val);
if(curAD < ret)
{
ret = curAD;
}
}
pre = root;
inOrder(root->right,pre,ret);
}
};
上一篇: DOM原生遍历、获取、修改节点内容
下一篇: 浮动与清除浮动
推荐阅读
-
530. Minimum Absolute Difference in BST
-
Leetcode每日一题:530.minimum-absolute-difference-in-bst(二叉搜索树的最小绝对值)
-
530. Minimum Absolute Difference in BST
-
LC-Minimum Absolute Difference in BST
-
(Java)leetcode-530 Minimum Absolute Difference in BST (二叉搜索树的最小绝对差)
-
LeetCode之路:530. Minimum Absolute Difference in BST
-
530 - 二叉搜索树的最小绝对差(minimum-absolute-difference-in-bst)
-
530. Minimum Absolute Difference in BST
-
LeetCode 530. Minimum Absolute Difference in BST
-
Leetcode 530. Minimum Absolute Difference in BST