530. Minimum Absolute Difference in BST

Posted 高数考了59

tags:

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

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     int getMinimumDifference(TreeNode* root) 
21     {
22         stack<TreeNode*> s;
23         TreeNode *p=root;
24         int pre,mindiff=INT_MAX;
25         int count=1;
26         while(p||!s.empty())
27         {
28             if(p)
29             {
30                 s.push(p);
31                 p=p->left;
32             }
33             else
34             {
35                 p=s.top();
36                 if(count==1)
37                     pre=p->val;
38                 else
39                 {
40                     mindiff=min(p->val-pre,mindiff);
41                     pre=p->val;
42                 }
43                 s.pop();
44                 p=p->right;
45                 count++;
46             }
47         }
48         return mindiff;
49     }
50 };

利用中序遍历二叉排序树出来是个升序序列的特点,每访问一个节点,减去前面节点即为这个节点的最小差值。

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

[leetcode-530-Minimum Absolute Difference in BST]

Leetcode 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 Java

easy530. Minimum Absolute Difference in BST