llllmz

导航

236. 二叉树的最近公共祖先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) 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 && right) return root;
    if(left) return left;
    if(right) return right;
    if(!left && !right){
        if(root==p || root==q) return root;
    }

    return NULL;
}

 

posted on 2024-03-21 16:57  神奇的萝卜丝  阅读(1)  评论(0编辑  收藏  举报