|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
| 4 | + |
4 | 5 | import java.util.ArrayList;
|
5 | 6 | import java.util.List;
|
6 | 7 |
|
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 | 8 | 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); |
| 9 | + public static class Solution1 { |
| 10 | + public int minDiffInBST(TreeNode root) { |
| 11 | + List<Integer> inorder = new ArrayList<>(); |
| 12 | + inorder(root, inorder); |
| 13 | + return findMinDiff(inorder); |
| 14 | + } |
| 15 | + |
| 16 | + private int findMinDiff(List<Integer> inorder) { |
| 17 | + int minDiff = Integer.MAX_VALUE; |
| 18 | + for (int i = 1; i < inorder.size(); i++) { |
| 19 | + minDiff = Math.min(minDiff, inorder.get(i) - inorder.get(i - 1)); |
| 20 | + } |
| 21 | + return minDiff; |
| 22 | + } |
| 23 | + |
| 24 | + private void inorder(TreeNode root, List<Integer> inorder) { |
| 25 | + if (root == null) { |
| 26 | + return; |
| 27 | + } |
| 28 | + inorder(root.left, inorder); |
| 29 | + inorder.add(root.val); |
| 30 | + inorder(root.right, inorder); |
| 31 | + } |
58 | 32 | }
|
59 |
| - } |
60 | 33 | }
|
0 commit comments