Java实现 LeetCode 530 二叉搜索树的最小绝对差(遍历树)

530. 二叉搜索树的最小绝对差

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

示例:

输入:

   1
    \
     3
    /
   2

输出:
1

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

PS:
递归遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int result = Integer.MAX_VALUE; private TreeNode preNode = null;
    public int getMinimumDifference(TreeNode root) {
    
    getMin(root);
    return result;
}

private void getMin(TreeNode root){
    if(root == null){
        return;
    }
    getMin(root.left);
    if(preNode != null)
    {
        result = Math.min(Math.abs(root.val - preNode.val), result);
    }
    preNode = root;
    getMin(root.right);
}
}
发布了1621 篇原创文章 · 获赞 2万+ · 访问量 269万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/105068622
今日推荐