LeetCode 530. 二叉搜索树的最小绝对差

二叉搜索树的最小绝对差

题目描述:
给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。

题目分析:根据二叉搜索树的性质可得,按中序遍历,即可得到一个递增的序列,所以问题转换为,对于一个递增的序列,求相邻元素的最小绝对差。

代码如下:

void inorder(TreeNode *root, int & min, int & pre){   //min为相邻元素最小差,pre为前一个元素
	if(root != NULL){
		inorder(root->left, min, pre);
		if(pre != -1)
			if(root->val-pre < min)
				min = root->val-pre;
		pre = root->val;
		inorder(root->right, min, pre);
	}
}
int getMinimumDifference(TreeNode *root){
	int min = 10000, pre = -1;                        //初始min设为一个足够大的值,pre设为-1
	inorder(root, min, pre);
	return min;
}

猜你喜欢

转载自blog.csdn.net/qq_41748387/article/details/83212105
今日推荐