一、236. 二叉树的最近公共祖先

C++数据结构与算法——二叉树公共祖先问题-LMLPHP

/**
 * 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) {
        // 判断一个节点左子树右子树是否同时包含pq即可
        if(root==p||root==q||root==NULL) return root;
        TreeNode * left = lowestCommonAncestor(root->left,p,q);
        TreeNode * right = lowestCommonAncestor(root->right,p,q);
        if(left!=NULL&&right!=NULL) return root;
        else if(left!=NULL&&right==NULL) return left;
        else if(left==NULL&&right!=NULL) return right;
        else return NULL;
    }


};

C++数据结构与算法——二叉树公共祖先问题-LMLPHP

二、235. 二叉搜索树的最近公共祖先

C++数据结构与算法——二叉树公共祖先问题-LMLPHP

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        // 判断一个节点左子树右子树是否同时包含pq即可
        if(root==p||root==q||root==NULL) return root;
        TreeNode * left = lowestCommonAncestor(root->left,p,q);
        TreeNode * right = lowestCommonAncestor(root->right,p,q);
        if(left!=NULL&&right!=NULL) return root;
        else if(left!=NULL&&right==NULL) return left;
        else if(left==NULL&&right!=NULL) return right;
        else return NULL;
    }


};

C++数据结构与算法——二叉树公共祖先问题-LMLPHP

04-05 16:36