求二分查找树的最小公共先驱。知道了什么叫二分查找树这道题就很好写了,逻辑还是比较简单的,比较node值与目标值的区间决定左移或右移就行。
如下:
void lowestCA(struct TreeNode *node, int low, int high, struct TreeNode **result) {
if (node == NULL)
return;
if (node->val >= low && node->val <= high) {
*result = node;
return;
}
else if (node->val > high)
lowestCA(node->left, low, high, result);
else if (node->val < high)
lowestCA(node->right, low, high, result);
}
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
struct TreeNode *result = (struct TreeNode *)malloc(sizeof(struct TreeNode));
memset(result, 0, sizeof(struct TreeNode));
int low = 0, high = 0;
if (p->val <= q->val)
low = p->val, high = q->val;
else
low = q->val, high = p->val;
lowestCA(root, low, high, &result);
return result;
}