题目来源
题目描述
题目解析
中序遍历是一个升序数组,而最小值的产生一定是在数组中相邻两个元素的差之中,因此,在中序遍历时候抓住前一个数,和当前数字的差 于最小值作比较
递归
一定需要遍历所有节点,因为不知道到底是哪两个节点之间产生的。
用一个辅助链表,将中序遍历得到的值压入链表中,然后得到两个节点之间的值
class Solution {
private:
vector<int> vec;
void traversal(TreeNode* root) {
if (root == NULL) return;
traversal(root->left);
vec.push_back(root->val); // 将二叉搜索树转换为有序数组
traversal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
vec.clear();
traversal(root);
if (vec.size() < 2) return 0;
int result = INT_MAX;
for (int i = 1; i < vec.size(); i++) { // 统计有序数组的最小差值
result = min(result, vec[i] - vec[i-1]);
}
return result;
}
};
我们不需要所有链表的节点,只需要得到一个最小值就行了
class Solution {
int ans = INT_MAX;
TreeNode*pre = nullptr;
void helper(TreeNode* root){
if(root == nullptr){
return;
}
helper(root->left);
if(pre != nullptr){
ans = std::min(ans, root->val - pre->val);
}
pre = root;
helper(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
helper(root);
return ans;
}
};
辅助栈
中序递归的栈实现
/**
* 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) {
int ans = Integer.MAX_VALUE;
TreeNode pre = null;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()){
TreeNode top = stack.pop();
if (top != null){
if (top.right != null){
stack.push(top.right);
}
stack.push(top);
stack.push(null);
if (top.left != null){
stack.push(top.left);
}
}else{
top = stack.pop();
if (pre != null){
int t = top.val - pre.val;
if (ans > t){
ans = t;
}
}
pre = top;
}
}
return ans;
}
}
这道题考的是中序遍历,【层次遍历和中序遍历是不一样的】