思路: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;
    }
};

 

相关文章:

  • 2021-06-24
  • 2021-12-05
  • 2021-12-28
  • 2022-12-23
  • 2021-06-11
  • 2022-01-23
  • 2021-07-18
  • 2021-11-02
猜你喜欢
  • 2021-10-12
  • 2021-08-30
  • 2021-08-15
  • 2021-12-12
  • 2021-07-02
相关资源
相似解决方案