Difference between binary search and binary search tree?

前端 未结 4 1206
攒了一身酷
攒了一身酷 2021-01-30 07:24

What is the difference between binary search and binary search tree?

Are they the same? Reading the internet it seems the second is only for trees (up to 2 children node

4条回答
  •  情话喂你
    2021-01-30 07:59

    1. to search for an element using binary search the elements should be represented in sequential memory locations like using an array where u need to know the size of the array to find the middle element to search using binary search tree we need not have the data in sequential locations .. we need to add elements into a BST node ... each BST node contains its right and left child so knowing the root is enough to conduct a search on the tree

    2. since u use an array for binary search the insertion and deletion will be easy but in BST we need to traverse through the height of tree even in worst case

    3. To do binary search we need the elements to be in sorted order but BST doesn't follow this rule

    4. Now coming to the searching time complexities ..

      a) using binary search the worst case complexity is O(logn)

      b) using BST the worst case complexity is O(n) i.e., if the tree is skewed then it just works like a linked list and we end up searching all the elements(thats why we need to implement balanced BSTs)

    5. Binary search needs O(1) space complexity since the locations are consecutive .. BST needs O(n) space for each node we need extra space to store the pointer of its child nodes

提交回复
热议问题