1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         if(root==nullptr||p==nullptr||q==nullptr)
14             return nullptr;
15         if(root==p)
16             return root;
17         if(root==q)
18             return root;
19         TreeNode* left=lowestCommonAncestor(root->left,p,q);
20         TreeNode* right=lowestCommonAncestor(root->right,p,q);
21         if(left&&right)
22             return root;
23         return left?left:right;
24     }
25 };

 

相关文章:

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