783. Minimum Distance Between BST Node

Posted zhuangbijingdeboke

tags:

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

方法一,非递归方法,中序遍历

 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 
11 static int wing=[]()
12 {
13     std::ios::sync_with_stdio(false);
14     cin.tie(NULL);
15     return 0;
16 }();
17 
18 class Solution 
19 {
20 public:
21     
22     int minDiffInBST(TreeNode* root) 
23     {
24         stack<TreeNode*>s;
25         int mindiff=INT_MAX;
26         TreeNode *p=root;
27         int pre=-(root->val),cur=0;
28         while(p||!s.empty())
29         {
30             if(p)
31             {
32                 s.push(p);
33                 p=p->left;
34             }
35             else
36             {
37                 p=s.top();
38                 s.pop();
39                 cur=p->val;
40                 mindiff=min(mindiff,cur-pre);
41                 pre=cur;
42                 p=p->right;
43             }
44         }
45         return mindiff;
46     }
47 };

方法二,递归方法,中序遍历

 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 
11 static int wing=[]()
12 {
13     std::ios::sync_with_stdio(false);
14     cin.tie(NULL);
15     return 0;
16 }();
17 
18 class Solution {
19     int dif=INT_MAX, val=-1;
20 public:
21     int minDiffInBST(TreeNode* root)    
22  {
23         if(root->left!=nullptr) 
24             minDiffInBST(root->left);
25         if(val>=0) dif=min(dif,root->val-val);
26             val=root->val;
27         if(root->right!=nullptr)
28             minDiffInBST(root->right);
29         return dif;
30     }
31     
32 };

简单,问题不大

以上是关于783. Minimum Distance Between BST Node的主要内容,如果未能解决你的问题,请参考以下文章

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Node

[leetcode-783-Minimum Distance Between BST Nodes]

783. Minimum Distance Between BST Nodes - Easy