当前位置:网站首页>Leetcode minimum absolute difference of binary search tree simple

Leetcode minimum absolute difference of binary search tree simple

2022-06-13 05:49:00 AnWenRen

title :530 The minimum absolute difference of binary search tree - Simple

subject

Give you a binary search tree root node root , return The minimum difference between the values of any two different nodes in the tree .

The difference is a positive number , Its value is equal to the absolute value of the difference between the two values .

Example 1

 Input :root = [4,2,6,1,3]
 Output :1

Example 2

 Input :root = [1,0,48,null,null,12,49]
 Output :1

Tips

  • The number of nodes in the tree ranges from [2, 104]
  • 0 <= Node.val <= 105

Code Java

int pre;
int ans;
public int getMinimumDifference(TreeNode root) {
    
    pre = -1;
    ans = Integer.MAX_VALUE;
    inOrder(root);
    return ans;
}
//  Middle order traversal to obtain the minimum value 
public void inOrder(TreeNode root) {
    
    if (root == null) return;
    inOrder(root.left);
    if (pre == -1)
        pre = root.val;
    else {
    
        ans = Math.min(ans, root.val - pre);
        pre = root.val;
    }
    inOrder(root.right);
}
原网站

版权声明
本文为[AnWenRen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280507175059.html