Leetcode 236

思路:1.如果p或q就是根节点,那么LCA=p或q,返回根节点(递归出口)

2.分治

   2.1 Divide:分别计算左字树和右子树的LCA

   2.2 Conquer:如果左字树和右子树的计算结果均不为空,则根节点就是p,q的LCA;如果左不为空而右为空,则返回左子树的计算结果;

   如果右不为空而左为空,则返回右子树的计算结果。如果左右子树均为空,则返回空指针

/**
 * 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==NULL) return NULL;
        if(p==root||q==root) return root;
        TreeNode *left=lowestCommonAncestor(root->left,p,q);
        TreeNode *right=lowestCommonAncestor(root->right,p,q);
        if(left!=NULL&&right!=NULL) return root;
        if(left!=NULL) return left;
        if(right!=NULL) return right;
        return NULL;
    }
};
原文地址:https://www.cnblogs.com/freinds/p/6307741.html