方法一,非递归方法,中序遍历
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 stacks;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 else36 {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 };
简单,问题不大