-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL783.java
More file actions
37 lines (32 loc) · 1.2 KB
/
L783.java
File metadata and controls
37 lines (32 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution783 {
class Solution {
private int minDiff = Integer.MAX_VALUE;
private TreeNode previous;
/**
* 783. Minimum Distance Between BST Nodes https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/
* Inorder traversal of a BST processes the nodes in sorted order. We maintain the previously seen element while traversing
* and compare with min seen so far to keep track of the min difference.
*
* @param root TreeNode
* Root of the tree
* @return Min difference between any two nodes
* @timeComplexity O(n) where n is the number of nodes in tree
* @spaceComplexity O(1)
*/
public int minDiffInBST(TreeNode root) {
if (root == null) {
return minDiff;
}
// Traverse left
minDiffInBST(root.left);
// Traverse root
if (previous != null) {
minDiff = Math.min(minDiff, root.val - previous.val);
}
previous = root;
// Traverse right
minDiffInBST(root.right);
return minDiff;
}
}
}