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

本文最后更新于:2021年2月15日 下午

给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
输入:

1
\
3
/
2

输出:
1

解释:
最小绝对差为 1,其中 2 1 的差的绝对值为 1(或者 2 和 3)。

提示:

Solution

  • 递归法
  • 利用二叉搜索树的性质,可以中序遍历存入 vector,再比较
  • 或者设置 pre 节点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res = INT_MAX;
TreeNode* pre = nullptr;

void traversal(TreeNode* cur) {
if (cur == nullptr) return;
traversal(cur->left);
if (pre != nullptr) {
res = min(res, cur->val - pre->val);
}
pre = cur;
traversal(cur->right);
}

int getMinimumDifference(TreeNode* root) {
traversal(root);
return res;
}
};
// @lc code=end
  • 迭代法,中序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
stack<TreeNode *> stack;
TreeNode* cur = root;
TreeNode* pre = NULL;
int res = INT_MAX;
while (cur || !stack.empty()) {
while (cur) {
stack.push(cur);
cur = cur->left;
}
cur = stack.top();
stack.pop();
if (pre != NULL) {
res = min(res, cur->val - pre->val);
}
pre = cur;
cur = cur->right;
}
return res;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!