您的位置:首页 > 其它

Lowest Common Ancestor of Binary Search Tree (BST)

2013-09-09 22:12 190 查看
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;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: