Find the nearest ancestor

1. Binary search tree

Can search on the nature of the binary search tree, steps are as follows:

(1) determines whether the empty root

(2) Comparison of the child node p, q of size, such as the right node of the root q;

(3) determining p, q whether the node is a root node, if the p (q) return;

(4) using the properties of binary search on the number of recursive calls to your line

 

2. Ordinary binary tree

Steps are as follows:

(1) first determines whether a root node is empty;

(2) determining p, q whether the root node

(3) recursive calls from the left and right subtrees

 

3. Implementation code

//二叉搜索树

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


//普通二叉树


struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root == NULL) return NULL;
    if(root->val == p->val || root->val == q->val){
        return root->val == p->h? p : q;
    }
    struct TreeNode *temp1 = lowestCommonAncestor(root->left, p, q);
    struct TreeNode *temp2 = lowestCommonAncestor(root->right, p, q);
    if(temp1 == NULL && temp2 == NULL) return NULL;
    if(temp1 == NULl || temp2 == NULL){
        return temp1 == NULL ? temp2 : temp2;
    }
    return root;
}

 

Guess you like

Origin www.cnblogs.com/spontanous/p/11770487.html