235-e-Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:js可以控制浏览器比例 编辑:程序博客网 时间:2024/05/21 06:20

求二分查找树的最小公共先驱。知道了什么叫二分查找树这道题就很好写了,逻辑还是比较简单的,比较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;}


0 0
原创粉丝点击