首页 > 其他 > 详细

Binary Search Tree

时间:2019-10-12 14:31:57      阅读:65      评论:0      收藏:0      [点我收藏+]

Insert

insert这里实现是return Node *,也可以用 void insert(Node *&root, int key),利用指针的引用来做。

Node *insert(Node *root, int key){
    if (root==NULL) return new Node(key);
    // do not allow duplicates
    if (key < root->val)
        root->left = insert(root->left,key);
    else if (key > root->val)
        root->right = insert(root->right, key);
    return root;
};

时间复杂度 O(h),h是二叉树高度

Search

bool search(Node *root, int key){
    if (root==NULL) return false;
    if (key<root->val) return search(root->left,key);
    else if (key>root->val) return search(root->right,key);
    return true;
}

时间复杂度 O(h)

 

 

Reference

https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/

https://www.geeksforgeeks.org/binary-search-tree-set-2-delete/

Binary Search Tree

原文:https://www.cnblogs.com/hankunyan/p/11661121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!