二叉搜索树的最小绝对差
题目
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
示例:
输入:
1
\
3
/
2
输出:
1
解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
思路
本题要求二叉搜索树任意两节点差的绝对值的最小值,而我们知道二叉搜索树有个性质为二叉搜索树中序遍历得到的值序列是递增有序的,因此我们只要得到中序遍历后的值序列即能用上文提及的方法来解决。
C++代码
#include <bits/stdc++.h> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int ans = INT_MAX; int pre = -1; void inorder(TreeNode *root, int &pre, int ans) { if (root == NULL) return; inorder(root->left, pre, ans); if (pre == -1) { pre = root->val; } else { ans = min(root->val - pre, ans); pre = root->val; } inorder(root->right, pre, ans); } int getMinimumDifference(TreeNode *root) { inorder(root, pre, ans); return ans; } };
Golang代码
func min(x, y int) int { if x <= y { return x } else { return y } } func inorder(root *TreeNode, pre, ans *int) { inorder(root.Left, pre, ans) if *pre == -1 { *pre = root.Val } else { *ans = min(root.Val-*pre, *ans) *pre = root.Val } inorder(root.Right, pre, ans) } func getMinimumDifference(root *TreeNode) int { pre := -1 ans := 1000000000 inorder(root, &pre, &ans) return ans }