Lowest Common Ancestor of Binary Search Tree (BST)
Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.
Thoughts:
1. 两个节点在同一个子树(左子树,右子树), recursive搜索
2. 不在同一个子树,当下的根节点就是他们的共同节点
Solution:
Node* findLCA(Node *tree, Node *n1, Node *n2) { if(!tree || !n1 || !na) return NULL; else if (max(n1->val, n2->val) > tree->val) findLCA(tree->right, n1, n2); else if(min(n1->val, n2->val) < tree->val) findLCA(tree->left, n1, n2); else return tree; }