-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
janky-ahh solution to find the minimum difference between nodes in a binary search tree, could be very easily optimised but im not gonna right now
- Loading branch information
1 parent
70efb2c
commit aef51cb
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
# Definition for a binary tree node. | ||
# class TreeNode: | ||
# def __init__(self, val=0, left=None, right=None): | ||
# self.val = val | ||
# self.left = left | ||
# self.right = right | ||
class Solution: | ||
def minDiffInBST(self, root_node: Optional[TreeNode]) -> int: | ||
|
||
def search(root: Optional[TreeNode], prevs: List[int]) -> int: | ||
if len(prevs) > 0: | ||
prevdiff = min([abs(root.val - prev) for prev in prevs]) | ||
else: | ||
prevdiff = math.inf | ||
#print(root.val, prevs, prevdiff) | ||
if root.left == None and root.right == None: | ||
return prevdiff | ||
elif root.left == None and root.right != None: | ||
return min([abs(root.val - root.right.val), search(root.right, prevs + [root.val]), prevdiff]) | ||
elif root.right == None and root.left != None: | ||
return min([abs(root.val - root.left.val), search(root.left, prevs + [root.val]), prevdiff]) | ||
else: | ||
return min([search(root.left, prevs + [root.val]), search(root.right, prevs + [root.val]), abs(root.val - root.left.val), abs(root.val - root.right.val), prevdiff]) | ||
return search(root_node, []) | ||
|