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

结果:

posted on 2024-03-14 19:23  神奇的萝卜丝  阅读(9)  评论(0)    收藏  举报