今天这题发出来是因为建立测试的时候,是不能使用层序遍历插入的。只能使用二叉排序树的插入方式。
除此之外,二叉排序树的中序遍历就是排序好的数组,因此这题就很简单了
C++代码(附带测试)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode():val(0),left(nullptr),right(nullptr){}
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
TreeNode(int x,TreeNode *left,TreeNode *right) :val(x),left(left),right(right){}
};
TreeNode* insert(TreeNode* root,int data){
TreeNode* T;
if(root==nullptr){
T = new TreeNode(data);
return T;
}
if(data>root->val){
root->right = insert(root->right,data);
}
else{
root->left = insert(root->left,data);
}
return root;
}
TreeNode* create(vector<int> a){
TreeNode* root = new TreeNode(a[0]);
for(int i=1;i<a.size();i++){
root = insert(root,a[i]);
}
return root;
}
void inorder(TreeNode* root){
if(root==nullptr){
return;
}
inorder(root->left);
cout<<root->val<<" ";
inorder(root->right);
}
class Solution {//二叉排序数的中序遍历是有序的
public:
void inorder(TreeNode* root,int& pre,int& ans){
if(root==nullptr){
return;
}
inorder(root->left,pre,ans);
if(pre==-1){
pre = root->val;
}
else{
ans = min(ans,root->val-pre);
pre = root->val;
}
inorder(root->right,pre,ans);
}
int minDiffInBST(TreeNode* root) {
int ans = INT_MAX;
int pre = -1;
inorder(root,pre,ans);
return ans;
}
};
int main(){
vector<int> a = {27,34,58,50,44};
TreeNode* root = create(a);
inorder(root);
Solution solution;
cout<<endl;
cout<<"ans:"<<solution.minDiffInBST(root);
}