【LeetCode每日一题】783. 二叉搜索树节点最小距离
题目:
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
示例 1:
输入:root = [4,2,6,1,3]
输出:1
题解:
解法1:
存入数组中扫描。
class Solution {
public:
int INF = 1e5+9;
vector<int> res;
int minDiffInBST(TreeNode* root) {
inorder(root);
int ans = INF;
for (int i = 1; i < res.size(); i++) {
ans = min(ans, res[i]-res[i-1]);
}
return ans;
}
void inorder(TreeNode* root) {
if (!root) return;
if (root->left) inorder(root->left);
res.push_back(root->val);
if (root->right) inorder(root->right);
}
};
解法2:直接中序遍历拿到前一个结点比大小。
class Solution {
public:
int INF = 1e5+9;
int ans = INF;
TreeNode* pre = NULL;
int minDiffInBST(TreeNode* root) {
inorder(root);
return ans;
}
void inorder(TreeNode* root) {
if (!root) return;
if (root->left) {
inorder(root->left);
}
if (pre) {
ans = min(ans, root->val-pre->val);
}
pre = root;
if (root->right) {
inorder(root->right);
}
}
};
本节完~
往日每日一题:
【LeetCode每日一题】83. 删除排序链表中的重复元素
像树一样简单回溯递归【LeetCode每日一题】90. 子集 II
4月你好,愚人节果然是笨人,【LeetCode每日一题】1006. 笨阶乘
【LeetCode每日一题】面试题 17.21. 直方图的水量
不知不觉已经坚持8天了,你呢?【LeetCode每日一题】1143. 最长公共子序列
Day10【LeetCode每日一题】781. 森林中的兔子