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;
    }
};
posted @ 2020-05-10 11:15  Keane1998  阅读(149)  评论(0编辑  收藏  举报