Binary search tree: the nearest common ancestor of the binary search tree

Binary search tree: the nearest common ancestor of the binary search tree

Insert picture description here
Different from the binary tree: common ancestor problem, ordinary binary trees need to use backtracking to find the nearest common ancestor from the bottom to the top. The binary search tree is unnecessary, because the search tree is ordered (equivalent to its own direction). The next traversal will do.

Then we can use the preorder traversal (in fact, there is no processing logic of the middle node here, and the traversal order does not matter).

TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
    
    
        if (cur == NULL) return cur;
                                                        // 中
        if (cur->val > p->val && cur->val > q->val) {
    
       // 左
            TreeNode* left = traversal(cur->left, p, q);
            if (left != NULL) {
    
    
                return left;
            }
        }

        if (cur->val < p->val && cur->val < q->val) {
    
       // 右
            TreeNode* right = traversal(cur->right, p, q);
            if (right != NULL) {
    
    
                return right;
            }
        }
        return cur;
    }
    }

Simplified code:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
    
        if (root->val > p->val && root->val > q->val) {
    
    
            return lowestCommonAncestor(root->left, p, q);
        } else if (root->val < p->val && root->val < q->val) {
    
    
            return lowestCommonAncestor(root->right, p, q);
        } else return root;
    }

Iterative method:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
    
        while(root) {
    
    
            if (root->val > p->val && root->val > q->val) {
    
    
                root = root->left;
            } else if (root->val < p->val && root->val < q->val) {
    
    
                root = root->right;
            } else return root;
        }
        return NULL;
    }

Guess you like

Origin blog.csdn.net/cckluv/article/details/113091184