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

 

示例:

输入:

1
\
3
/
2

输出:
1

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int minVal = Integer.MAX_VALUE;
    int preVal = -1;

    //中序遍历:左子节点、根节点、右子节点
    //根据二叉搜索树的特性为:左子节点小于根节点、根节点小于右子节点

    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return minVal;
    }

    public void dfs(TreeNode root){
        if(root == null){
            return ;
        }
        if(minVal == 0){
            return;
        }
        
        dfs(root.left);

        if(preVal == -1){
            preVal = root.val;
        } else {
            minVal = Math.min(minVal, Math.abs(root.val - preVal));
            preVal = root.val;
        }
        dfs(root.right);
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-01-09
  • 2020-01-01
  • 2021-11-17
  • 2022-03-01
  • 2022-01-30
  • 2022-02-26
  • 2021-05-17
猜你喜欢
  • 2021-06-30
  • 2021-05-31
  • 2021-08-30
  • 2021-10-16
  • 2021-10-23
  • 2021-05-30
  • 2018-10-10
相关资源
相似解决方案