|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * 783. Minimum Distance Between BST Nodes |
| 9 | + * |
| 10 | + * Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. |
| 11 | +
|
| 12 | + Example : |
| 13 | +
|
| 14 | + Input: root = [4,2,6,1,3,null,null] |
| 15 | + Output: 1 |
| 16 | + Explanation: |
| 17 | + Note that root is a TreeNode object, not an array. |
| 18 | +
|
| 19 | + The given tree [4,2,6,1,3,null,null] is represented by the following diagram: |
| 20 | +
|
| 21 | + 4 |
| 22 | + / \ |
| 23 | + 2 6 |
| 24 | + / \ |
| 25 | + 1 3 |
| 26 | +
|
| 27 | + while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2. |
| 28 | +
|
| 29 | + Note: |
| 30 | +
|
| 31 | + The size of the BST will be between 2 and 100. |
| 32 | + The BST is always valid, each node's value is an integer, and each node's value is different. |
| 33 | + */ |
| 34 | + |
| 35 | +public class _783 { |
| 36 | + public static class Solution1 { |
| 37 | + public int minDiffInBST(TreeNode root) { |
| 38 | + List<Integer> inorder = new ArrayList<>(); |
| 39 | + inorder(root, inorder); |
| 40 | + return findMinDiff(inorder); |
| 41 | + } |
| 42 | + |
| 43 | + private int findMinDiff(List<Integer> inorder) { |
| 44 | + int minDiff = Integer.MAX_VALUE; |
| 45 | + for (int i = 1; i < inorder.size(); i++) { |
| 46 | + minDiff = Math.min(minDiff, inorder.get(i) - inorder.get(i - 1)); |
| 47 | + } |
| 48 | + return minDiff; |
| 49 | + } |
| 50 | + |
| 51 | + private void inorder(TreeNode root, List<Integer> inorder) { |
| 52 | + if (root == null) { |
| 53 | + return; |
| 54 | + } |
| 55 | + inorder(root.left, inorder); |
| 56 | + inorder.add(root.val); |
| 57 | + inorder(root.right, inorder); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments