0% found this document useful (0 votes)
44 views1 page

Leetcode 530. Minimum Absolute Difference in BST

This document defines a binary tree node class and provides a Solution class to find the minimum difference between any two adjacent nodes in an in-order traversal of the tree. The getMinimumDifference method performs an in-order traversal of the tree using an inorder helper method, tracking the minimum difference seen between each node and its predecessor and returning the final minimum.

Uploaded by

Weihao Zhang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views1 page

Leetcode 530. Minimum Absolute Difference in BST

This document defines a binary tree node class and provides a Solution class to find the minimum difference between any two adjacent nodes in an in-order traversal of the tree. The getMinimumDifference method performs an in-order traversal of the tree using an inorder helper method, tracking the minimum difference seen between each node and its predecessor and returning the final minimum.

Uploaded by

Weihao Zhang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# 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:
mini = float("inf")
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
# What we need to do is in-order traverse the tree and then find the difference
between two adjacent node. Then, return the minimal one.
self.inorder(root, None)
return self.mini

def inorder(self, cur, pre):


# Thus, the base condition is when the node == null, then we have taversed the
whole tree
if cur == None:
return None
print(cur.val)
self.inorder(cur.left, pre)
if pre != None:
if cur.val - pre.val < self.mini:
self.mini = cur.val - pre.val
print(pre.val)
pre = cur
self.inorder(cur.right, pre)

You might also like