Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
<Solution>想法如下
- 因為是BST,所以用 inorder traversal 會得到一個由小到大的數列。因此,在歷遍的時候,檢查當下的值減掉前面的值,並記錄最小的差距,歷遍結束後就會得到答案。這是因為數列是排序的,最小值一定是兩個相鄰的數相減來得到的
C++(使用遞迴)
Java(使用 stack)
沒有留言:
張貼留言