1. Description
Given the root of Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
constraints :
- The number of nodes in the tree is in the range [2, \(10^{4}\)].
- 0 <= Node.val <= \(10^{5}\)
2. Algorithms
To store all values of nodes into one array, we need to traverse through the tree. If we use inorder tree traversal, we can get sorted values of array.
Because the array from tree is sorted, we just compare the difference of adjacent values repeatedly.
- Start
- Declare variable named inorder initialized with empty list.
- Declare function named helper which got root as input.
- If root,
- Traverse left child of root recursively.
- Append the value of root to list.
- Traverse right child of root recursively.
- If root,
- Operate helper function.
- Declare variable named min_diff initialized with 2**32.
- Repeat the steps through integers 1 to len(inorder) - 1.
- Calculate diff of integer[i] and integer[i + 1].
- Update min_diff as min between min_diff and diff.
- Return min_diff after the loop ends.
- End
3. Codes
# 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 getMinimumDifference(self, root: Optional[TreeNode]) -> int:
# inorder : list, stores the value of input tree in sorted format.
inorder = []
def helper(root) :
if root :
helper(root.left)
inorder.append(root.val)
helper(root.right)
helper(root)
min_diff = 2**32
for i in range(len(inorder) - 1) :
diff = inorder[i+1] - inorder[i]
min_diff = min(min_diff, diff)
return min_diff
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
543 Diameter of Binary Tree (0) | 2022.09.05 |
---|---|
541 Reverse String II (0) | 2022.09.05 |
521 Longest Uncommon Subsequence I (0) | 2022.09.04 |
520 Detect Capital (0) | 2022.09.03 |
511 Game Play Analysis I (0) | 2022.09.03 |