llllmz

导航

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

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* preorder(struct TreeNode* root,struct TreeNode* p,struct TreeNode* q){
    if(!root) return NULL;
    if(root==p) return p;
    if(root==q) return q;
    struct TreeNode* left=preorder(root->left,p,q);
    struct TreeNode* right=preorder(root->right,p,q);
    if(!right&&!left) return NULL;
    if(left==p&&right==q || left==q&&right==p) return root;
    if(left&&!right) return left;
    return right;
 } 


struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root==p||root==q) return root;
    return preorder(root,p,q);
}

结果:

posted on 2024-03-06 20:02  神奇的萝卜丝  阅读(15)  评论(0)    收藏  举报