题解 | #牛群最小体重差#
牛群最小体重差
https://www.nowcoder.com/practice/e96bd1aad52a468d9bff3271783349c1
考察知识点: 二叉搜索树、中序遍历、深度优先搜索
题目分析:
注意题目给出的是二叉搜索树
,这种结构有一个性质:二叉搜索树的中序遍历是递增序列
,又因为两个数之间的最小差值只可能是单调序列
中相邻两个数
之间的差值,所以我们可以中序遍历
一遍这个二叉搜索树,遍历时维护上一个访问的节点
的值,并维护最小体重差
。
所用编程语言: C++
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ void traverse(TreeNode *root, int &res, int last) { if (!root) return; traverse(root->left, res, last); if (last != -1) { res = min(res, root->val - last); } last = root->val; traverse(root->right, res, last); } int getMinimumDifference(TreeNode* root) { // write code here int res = 0x3f3f3f3f; traverse(root, res, -1); return res; } };