530. 二叉搜索树的最小绝对差
解: 递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void travel(struct TreeNode *node, int *array, int *idx) {
if (node == NULL) return;
travel(node->left, array, idx);
array[(*idx)++] = node->val;
travel(node->right, array, idx);
}
int getMinimumDifference(struct TreeNode* root) {
int array[10005] = {0};
int idx = 0;
travel(root, array, &idx);
for (int i = 0; i < idx; i++) printf("%d\n", array[i]);
int min = 0x3f3f3f;
for (int i = 1; i < idx; i++) {
if (array[i] - array[i-1] < min) {
min = array[i] - array[i-1];
}
}
return min;
}
解: 迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct stack {
int top;
struct TreeNode *array[10005];
};
int getMinimumDifference(struct TreeNode* root) {
int min = 0x3f3f3f;
struct TreeNode *pre = NULL, *node = root;
struct stack *st = (struct stack *)malloc(sizeof(*st));
memset(st, 0, sizeof(*st));
st->top = -1;
while (st->top != -1 || node != NULL) {
while (node != NULL) {
st->array[++st->top] = node;
node = node->left;
}
node = st->array[st->top--];
if (pre != NULL) {
if (min > node->val - pre->val) {
min = node->val - pre->val;
}
}
pre = node;
node = node->right;
}
return min;
}
501. 二叉搜索树中的众数
解
/**
* 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 cnt = 0;
int maxcnt = 0;
struct TreeNode *pre = NULL;
int *array = NULL;
int idx = 0;
void travel(struct TreeNode *node) {
if (node == NULL) return;
travel(node->left);
if (pre == NULL) {
cnt = 1;
} else if (pre->val == node->val) {
cnt++;
} else {
cnt = 1;
}
pre = node;
if (cnt == maxcnt) {
array[idx++] = node->val;
}
if (cnt > maxcnt) {
maxcnt = cnt;
idx = 0;
array[idx++] = node->val;
}
travel(node->right);
}
int* findMode(struct TreeNode* root, int* returnSize) {
cnt = maxcnt = idx = 0;
pre = NULL;
array = (int *)malloc(sizeof(int) *10005);
memset(array, 0, sizeof(int) * 10005);
*returnSize = 0;
if (root == NULL) return array;
travel(root);
*returnSize = idx;
return array;
}
leetcode中的全局变量并不是真正的全局变量, 每次都需要重置.
236. 二叉树的最近公共祖先
解
/**
* 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 == q || root == p || root == NULL) return root;
struct TreeNode *left = lowestCommonAncestor(root->left, p, q);
struct TreeNode *right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root;
if (left != NULL && right == NULL) return left;
else if (left == NULL && right != NULL) return right;
else return NULL;
}