leetcode 530. 二叉搜尋樹的最小絕對差(python)
阿新 • • 發佈:2018-12-24
給定一個所有節點為非負值的二叉搜尋樹,求樹中任意兩節點的差的絕對值的最小值。
示例 :
輸入:
1
\
3
/
2
輸出:
1
解釋:
最小絕對差為1,其中 2 和 1 的差的絕對值為 1(或者 2 和 3)。
注意: 樹中至少有2個節點。
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ self.val = None self.ans = float("inf") def inorder(root): if not root: return inorder(root.left) if self.val is not None: self.ans = min(self.ans, abs(root.val - self.val)) self.val = root.val inorder(root.right) inorder(root) return self.ans