leetcode剑指offer68II-二叉树的最近公共祖先(C语言实现)

leetcode剑指offer68II-二叉树的最近公共祖先(C语言实现)

/**
 * 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 == NULL) 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 != NULL && right != NULL) return root;
    if(right != NULL ) return right;
    if(left != NULL) return left;
    
    return NULL;

}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页