Leetcode_236. 二叉树的最近公共祖先
求二叉树的LCA
code
/**
* 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==p || root==q || root==NULL){
return root;
}
auto le=lowestCommonAncestor(root->left,p,q);
auto ri=lowestCommonAncestor(root->right,p,q);
if(!le){
return ri;
}
if(!ri){
return le;
}
return root;
}
};