LeetCode 530 Minimum Absolute Difference in BST

  • 2019 年 12 月 29 日
  • 筆記

题意

给予一颗非负二叉搜索树, 返回任意两个节点之间的最小相差值.

注: 树至少有两个节点.

例 :

给予树:         1             4      /      2   7      返回: 1 (1 和 2 之间相差 1).

解法

因为是一颗二叉搜索树, 所以采用中序遍历可以得到所有值从小到大的排列, 那么将每个节点与上个节点的值 prev 进行比较得出相差值 answer, 判断相差值与上个相差值, 将更小的存起来. 直到遍历完整棵树.

/**   * Definition for a binary tree node.   * public class TreeNode {   *     int val;   *     TreeNode left;   *     TreeNode right;   *     TreeNode(int x) { val = x; }   * }   */  class Solution {      private int prev = -1;      private int answer = Integer.MAX_VALUE;      public int getMinimumDifference(TreeNode root) {          if (root.left != null) {              getMinimumDifference(root.left);          }            if (prev != -1) {              answer = Math.min(answer, root.val - prev);          }            prev = root.val;            if (root.right != null) {              getMinimumDifference(root.right);          }          return answer;      }  }

Runtime: 1 ms, faster than 95.95% of Java online submissions for Minimum Absolute Difference in BST. Memory Usage: 38.4 MB, less than 97.37% of Java online submissions for Minimum Absolute Difference in BST.