[leetcode-530-Minimum Absolute Difference in BST]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-530-Minimum Absolute Difference in BST]相关的知识,希望对你有一定的参考价值。

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
  \
  3
 /
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

思路:

中序遍历能得到有序数列,而且最小差一定出现在相邻元素。

void zhongxubianli(TreeNode* root, vector<int>& tree)
     {
         if (root!=NULL)
         {
             zhongxubianli(root->left, tree);
             tree.push_back(root->val);
             zhongxubianli(root->right, tree);
         }
     }
     int getMinimumDifference(TreeNode* root)
     {
         vector<int>tree;
         zhongxubianli(root, tree);
         int ret = 100000;
         for (int i = 1; i < tree.size();i++)
         {
             ret = min(ret, tree[i] - tree[i - 1]);
         }
         return ret;
     }
     void zhongxubianli(TreeNode* root, int& ret,int& temp)
     {
         if (root!=NULL)
         {
             zhongxubianli(root->left, ret,temp);
             if(temp>=0)ret = min(ret, root->val - temp);
             temp = root->val;
             zhongxubianli(root->right, ret,temp);
         }
     }
     int getMinimumDifference(TreeNode* root)
     {
         int ret = 100000,temp = -1;
         zhongxubianli(root, ret,temp);         
         return ret;
     }

 












以上是关于[leetcode-530-Minimum Absolute Difference in BST]的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 530. Minimum Absolute Difference in BST Java

LeetCode 530. Minimum Absolute Difference in BST(在二叉查找树中查找两个节点之差的最小绝对值)

Python abs() 函数

ABS(x)

Python标准库:内置函数abs(x)

在 std::abs 函数上