给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
注意:本题与 530:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ 相同
中序遍历二叉搜索树,获取当前节点与上个节点的差值的最小值即可。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
def inorder(root):
if not root:
return
inorder(root.left)
if self.pre is not None:
self.min_diff = min(self.min_diff, abs(root.val - self.pre))
self.pre = root.val
inorder(root.right)
self.pre = None
self.min_diff = 10 ** 5
inorder(root)
return self.min_diff
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int minDiff = Integer.MAX_VALUE;
private Integer pre;
public int minDiffInBST(TreeNode root) {
inorder(root);
return minDiff;
}
private void inorder(TreeNode root) {
if (root == null) return;
inorder(root.left);
if (pre != null) minDiff = Math.min(minDiff, Math.abs(root.val - pre));
pre = root.val;
inorder(root.right);
}
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var res int
var preNode *TreeNode
func minDiffInBST(root *TreeNode) int {
res = int(^uint(0) >> 1)
preNode = nil
helper(root)
return res
}
func helper(root *TreeNode) {
if root == nil {
return
}
helper(root.Left)
if preNode != nil {
res = getMinInt(res, root.Val - preNode.Val)
}
preNode = root
helper(root.Right)
}
func getMinInt(a,b int) int {
if a < b {
return a
}
return b
}