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++(使用遞迴)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
int ans = INT_MAX; | |
int prv = -1; | |
int getMinimumDifference(TreeNode* root) { | |
return inorder(root); | |
} | |
int inorder(TreeNode *node) { | |
if(node == NULL) { | |
return ans; | |
} | |
inorder(node->left); | |
if(prv != -1) { | |
ans = min(ans, node->val - prv); | |
} | |
prv = node->val; | |
inorder(node->right); | |
return ans; | |
} | |
}; |
Java(使用 stack)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
class Solution { | |
public int getMinimumDifference(TreeNode root) { | |
Stack<TreeNode> stack = new Stack<>(); | |
int ans = Integer.MAX_VALUE; | |
while(root != null) { | |
stack.push(root); | |
root = root.left; | |
} | |
TreeNode node; | |
int prv = -1; | |
while(!stack.empty()) { | |
node = stack.pop(); | |
if(prv != -1) { | |
ans = Math.min(ans, node.val - prv); | |
} | |
prv = node.val; | |
if(node.right != null) { | |
node = node.right; | |
while(node != null) { | |
stack.push(node); | |
node = node.left; | |
} | |
} | |
} | |
return ans; | |
} | |
} |
沒有留言:
張貼留言