给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
注意题干中说明是二叉搜索树,所以要结合二叉搜索树的性质。
根节点的大小介于左孩子和右孩子之间。
其实 我们很容易就能看出来,和根节点差值最小的左子树的值,一定是左子树中最右边的节点。
同理,与根节点差值的最小的右子树的值,一定是右孩子中最左边的节点。
所以,中序遍历即可解答。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
// 中序遍历的非递归写法
stack<TreeNode *> st;
TreeNode *cur=root;
// 压栈
vector<int> vec;
int min_value=INT16_MAX;
while (cur!= nullptr||!st.empty()){
if(cur!= nullptr){
st.push(cur);
cur=cur->left;// 把左孩子 全部入栈
} else{
cur=st.top();
st.pop();
vec.push_back(cur->val);
cur=cur->right;//看向右孩子
}
}
for(int i=1;i<vec.size();i++){
int now=vec[i]-vec[i-1];
min_value= min(min_value,now);
}
return min_value;
}
};