Leetcode 783. 二叉搜索树结点最小距离
题目
给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。
示例:
输入: root = [4,2,6,1,3,null,null]
输出: 1
解释:
注意,root是树结点对象(TreeNode object),而不是数组。
给定的树 [4,2,6,1,3,null,null] 可表示为下图:
4
/ \
2 6
/ \
1 3
最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。
注意:
二叉树的大小范围在 2 到 100。
二叉树总是有效的,每个节点的值都是整数,且不重复。
链接: 力扣(LeetCode).
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
中序遍历比较最大值
代码
c++实现
虽然看起来不像中序遍历,但是好像确实是(有错欢迎指出)
int minDiffInBST(TreeNode* root) {
if(!root)//null节点返回极大值,显式表示不存在
return INT_MAX;
int le=INT_MAX,ri=INT_MAX;
TreeNode* child;
if(root->left)//左子树的最右端显然与根节点的差最小
{
child=root->left;
while(child->right)
child=child->right;
le=root->val-child->val;
}
if(root->right)//右子树的最左端显然与根基诶点的差最小
{
child=root->right;
while(child->left)
child=child->left;
ri=child->val-root->val;
}
int m=minDiffInBST(root->left);//递归计算所有节点的与其子树的最小差
int n=minDiffInBST(root->right);
return min(min(le,ri),min(m,n));//比较得出最小值
}
};
转载自Leetcode: mikiyashiki
python实现
def minDiffInBST(self, root):
in_order = lambda r: in_order(r.left) + [r.val] + in_order(r.right) if r else[]
vals = in_order(root)
return min([vals[i+1] - vals[i] for i in range(len(vals)-1)])
转载自Leetcode: SKX
java实现
class Solution {
private TreeNode pre = null; //pre记录前一节点
private int res = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
dfs(root);
return res;
}
private void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
if(pre != null){
res = Math.min(root.val-pre.val,res); //记录最小
}
pre = root;
dfs(root.right);
}
}
转载自Leetcode: Coding_Freshman