rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

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

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
/**
 * 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 TreeNode pre;
    private int ans = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return ans;
    }
    private void dfs(TreeNode root){
        if(root == null) return;
        dfs(root.left);
        if(pre != null){
            ans = Math.min(ans, root.val - pre.val);
        }
        pre = root;
        dfs(root.right);
    }
}