530.二叉搜索树的最小绝对差
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
示例:
输入:
1
\
3
/
2输出: 1
解释: 最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
本来是很简单的一道题,但是折腾了两个小时。。。因为一开始用栈用list,其中的一些函数都用不了。。如get()、pop_back()等。
最后还是用了数组。。。
首先二叉搜索树的特点就是,根节点的左子树比根节点小,右子树比根节点大。有了这个特点就可以对二叉搜索树进行排序。
按照左中右的顺序就可以将二叉树从小到大进行排序。
当左子树为空时,将该节点加入数组,然后将该节点的上一节点加入数组,然后右子树。。。
int order(TreeNode* root,int* num){
if(root == NULL){
return 0;
}
order(root->left,num);
num[count++] = root->val;
order(root->right,num);
return count;
}
代码如下:
/**
* 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 count = 0;
int getMinimumDifference(TreeNode* root) {
int num[1000000];
int i=0,min = 9999999;
count = order(root,num);
while(i<count-1){
if(min>(num[i+1]-num[i])){
min = num[i+1]-num[i];
}
i++;
}
return min;
}
int order(TreeNode* root,int* num){
if(root == NULL){
return 0;
}
order(root->left,num);
num[count++] = root->val;
order(root->right,num);
return count;
}
};
自己还是太菜了,还得多加练习,,,算法这一块我要定了。
加油,相信自己。
一个集坚强与自信于一身的菇凉。