剑指OFFER----面试题68 - II. 二叉树的最近公共祖先

链接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root) return root;
        if (root == p || root == q) return root;
        
        auto l = lowestCommonAncestor(root->left, p, q);
        auto r = lowestCommonAncestor(root->right, p, q);

        if (l && !r)     
            return l;      
        else if (r && !l) 
            return r;                  
        else if (l && r)  
            return root;  
        else             
            return NULL;  
    }
};

猜你喜欢

转载自www.cnblogs.com/clown9804/p/12512802.html