Python solution with detailed explanation


  • 0
    G

    Solution

    Minimum Absolute Difference in BST https://leetcode.com/problems/minimum-absolute-difference-in-bst/?tab=Description

    Inorder Traversal

    • Simple in-order traversal to track MAD.
    class Solution(object):
        def in_order(self, root):
            if root == None:
                return
            self.in_order(root.left)
            if self.prev is not None:
                self.min_abs = min(self.min_abs, abs(root.val-self.prev))
            self.prev = root.val
            self.in_order(root.right)
            return
        
        def getMinimumDifference(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.prev, self.min_abs = None, float('inf')
            self.in_order(root)
            return self.min_abs
    

  • 0
    V

    @gabbu said in Python solution with detailed explanation:

    if root == None:
    return
    self.in_order(root.left)
    if self.prev is not None:

    For better readability use:

    if not root: # implies if root is False(None)
        doSomething
    if self.prev: # implies self.prev is True(not None), you are using a double negative
        doSomething
    

  • 0
    G

    @Vincek3 Did you try your second optimization in OJ? There is a reason why "is not None" is used - but I will let you figure it out.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.