int countNodes(struct TreeNode* root) {
if (!root) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
void fillArray(struct TreeNode* root, int* nums, int* index) {
if (!root) return;
fillArray(root->left, nums, index);
nums[(*index)++] = root->val;
fillArray(root->right, nums, index);
}
int getMinimumDifference(struct TreeNode* root) {
if (!root) return 0;
int nodeCount = countNodes(root);
int* nums = (int*)malloc(nodeCount * sizeof(int));
int index = 0;
fillArray(root, nums, &index);
int minDiff = INT_MAX;
for (int i = 1; i < nodeCount; i++) {
int diff = nums[i] - nums[i - 1];
if (diff < minDiff) {
minDiff = diff;
}
}
return minDiff;
}
因为二叉搜查树是一个有序的,所以可以将存入一个数组里面,然后我们不断去对比
双指针
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void dfs (struct TreeNode* root, int* pre, int* ans){
if(!root)
return;
dfs(root->left, pre, ans);
if(*pre == -1){
*pre = root->val;
}
else
{
*ans = fmin(*ans, root->val-(*pre));
*pre = root->val;
}
dfs(root->right, pre, ans);
}
int getMinimumDifference(struct TreeNode* root) {
int ans = INT_MAX, pre = -1;
dfs(root, &pre, &ans);
return ans;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* answer;
int answerSize;
int base, count , maxCount;
void update(int x){
if( x == base){
++count;
}
else{
count = 1;
base = x;
}
if(count == maxCount){
answer[answerSize++] = base;
}
if(count > maxCount){
maxCount = count;
answerSize = 0;
answer[answerSize++] = base;
}
}
void dfs(struct TreeNode* node){
if(!node)
return;
dfs(node->left);
update(node->val);
dfs(node->right);
}
int* findMode(struct TreeNode* root, int* returnSize) {
base = count = maxCount = 0;
answer = malloc(sizeof(int)*4001);
answerSize = 0;
dfs(root);
*returnSize = answerSize;
return answer;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(!root)
return NULL;
if(root == p || root == q){
return root;
}
struct TreeNode* left = lowestCommonAncestor(root->left, p, q);
struct TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left && right)
return root;
if(!left && right){
return right;
}
else if(left && !right)
return left;
else
return NULL;
}