题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

//----------方法一开始
/*
void getPath(struct TreeNode* tree, int path[], int* k, int target) {
    int i = 0;
    int val = tree->val;
    while (val != target) {
        path[i++] = val;
        if (target < val) tree = tree->left;
        else tree = tree->right;
        val = tree->val;
    }
    path[i++] = val;
    *k = i;
}

int lowestCommonAncestor(struct TreeNode* root, int p, int q ) {
    int plist[10000], qlist[10000], k1 = 0, k2 = 0, res;
    getPath(root, plist, &k1, p);
    getPath(root, qlist, &k2, q);

    for (int i = 0; i < k1 && i < k2; i++) {
        if (plist[i] == qlist[i]) {
            res = plist[i];
        } else break;
    }
    return res;
}
*/
//---------------方法一结束

//---------------方法二开始
int lowestCommonAncestor(struct TreeNode* root, int p, int q) {
    // write code here
    struct TreeNode* cur = root;
    while (1) {
        if (p < cur->val && q < cur->val)
            cur = cur->left;
        else if (p > cur->val && q > cur->val)
            cur = cur->right;
        else break;
    }
    return cur->val;
}

//---------------方法二结束

全部评论

相关推荐

11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
努力成为C语言高手:质疑大祥老师,理解大祥老师,成为大祥老师
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务