【leetcode】236. 二叉树的最近公共祖先

 

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root==p || root==q || !root)
        return root;
    struct TreeNode* left = lowestCommonAncestor(root->left,p,q);
    struct TreeNode* right = lowestCommonAncestor(root->right,p,q);
    if(left && right){
        return root;
    }
    return (left)?left :right;
}

 

posted @ 2021-01-03 16:48  温暖了寂寞  阅读(53)  评论(0编辑  收藏  举报