Skip to content

Commit 97fa7f5

Browse files
author
rajitbanerjee
committed
minimum distance between bst nodes
1 parent 3792c44 commit 97fa7f5

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ My solutions to some problems from [LeetCode](https://leetcode.com/problemset/al
5151
| 617 | [Merge Two Binary Trees][617] | [Python][617a] | Easy |
5252
| 690 | [Employee Importance][690] | [Python][690a] | Easy |
5353
| 700 | [Search in a Binary Search Tree][700] | [Python][700a] | Easy |
54+
| 783 | [Minimum Distance Between BST Nodes][783] | [Python][783a] | Easy |
5455
| 788 | [Rotated Digits][788] | [Python][788a] | Easy |
5556
| 938 | [Range Sum of BST][938] | [Python][938a] | Easy |
5657
| 1029 | [Two City Scheduling][1029] | [Python][1029a] | Easy |
@@ -152,6 +153,8 @@ My solutions to some problems from [LeetCode](https://leetcode.com/problemset/al
152153
[690a]: ./src/empImportance/emp.py
153154
[700]: https://leetcode.com/problems/search-in-a-binary-search-tree/
154155
[700a]: ./src/searchBST/search.py
156+
[783]: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
157+
[783a]: ./src/minimumDistBST/dist.py
155158
[788]: https://leetcode.com/problems/rotated-digits/
156159
[788a]: ./src/rotatedDigits/dig.py
157160
[938]: https://leetcode.com/problems/range-sum-of-bst/

src/minimumDistBST/dist.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
9+
class Solution:
10+
def minDiffInBST(self, root: TreeNode) -> int:
11+
nodes = []
12+
13+
# traverse tree and store node values in list
14+
def trav(node) -> None:
15+
if node:
16+
nodes.append(node.val)
17+
trav(node.left)
18+
trav(node.right)
19+
trav(root)
20+
21+
nodes.sort()
22+
minDiff = nodes[-1] - nodes[0]
23+
# compute the minimum difference between two nodes
24+
for i in range(len(nodes) - 1):
25+
diff = nodes[i + 1] - nodes[i]
26+
if diff < minDiff:
27+
minDiff = diff
28+
29+
return minDiff

0 commit comments

Comments
 (0)