Binary Search Tree的LCA

In computer science, a binary search tree (BST) is a binary tree data structure which has the following properties:

  • Each node (item in the tree) has a distinct value.
  • Both the left and right subtrees must also be binary search trees.
  • The left subtree of a node contains only values less than the node's value.
  • The right subtree of a node contains only values greater than the node's value.

The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient.

Binary search trees can choose to allow or disallow duplicate values, depending on the implementation.

Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.

 

 

 

1. BST的搜索算法:

/* recursive method */
Node search(Node* node,Key key){
   if(NULL == node) return NULL;
    /*search the left tree*/
    if(key < node->key)
        search(node->lchid,key);
    else if(key > node->key)
        search(node->rchid,key);
    else
        return node;
}


/* iterative */
Node search(Node* node,Key key){
   if(NULL == node) return NULL;
    while(1){
         if(key < node->key)
            node = node->lchid;
         else if(key > node->key)
            node = node->rchid;
         else
            return node;
    }
}

 

2. BST的LCA(Least common ancestor)算法:

一般的binary tree的LCA算法:

1.从两个节点上溯,将路径中的节点分别压到两个stack中;

2.对两个stack中的栈顶的元素做比较。如果相同,pop掉元素,重复2。否则,则前一个相同元素就是LCA。

 

对于BST,它有一个重要的性质:节点的左子树包含且只包含比它小的节点,右子树包含且只包含比它大的节点。因此LCA的值一定在这两个节点之间。

1. 如果u<root && v<root,则节点就是LCA;

2. 如果u>root && v>root,则去右子树搜索;

3. 否则,root就是LCA

 

下面给出递归调用的算法:

Node search_LCA(Node* root, Node* u, Node*v){

    if(NULL == root) return NULL;

    if(root->key<u->key && root->key<v->key)

            search(root->left,u,v);

    elseif(root->key > u->key && root->key > v->key)

            search(root->right,u,v);

     else

            return root;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值