【LeetCode刷题笔记-89 783:二叉搜索树节点最小距离】

在这里插入图片描述
今天这题发出来是因为建立测试的时候,是不能使用层序遍历插入的。只能使用二叉排序树的插入方式。

除此之外,二叉排序树的中序遍历就是排序好的数组,因此这题就很简单了

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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值