简体   繁体   中英

How are nodes in binary search tree stored in java? and other questions related

I am trying to implement a binary search tree. But I do not understand how they would be stored within an array. This is the data structure I am storing it in :

private Comparable[] intHeap;

I am still unsure on how to use comparable, please could someone explain the use of this data structure?

How would I inspect the largest and smallest elements of the binary search tree?

If I had the following tree, would it be stored in the intHeap as 1,3,4,6,7,8,10,13,14?

How do you know which node to go to next, if there is multiple node levels?

二叉搜索树

Thank you in advance.

Judging from the declaration of an array, what you are building is a binary heap - a specialized tree-based data structure, which is typically stored in an array. Unlike tree structures that rely on explicit references, heaps rely on a clever indexing scheme that "packs" a tree into a linear data structure.

Comparable interface lets you build a heap that can store data of arbitrary classes, as long as they implement Comparable interface. This is useful, because you can build reusable code that works with numbers, strings, or objects of your own type.

How do you know which node to go to next, if there is multiple node levels?

If a node is at the index n , its two children would be at indexes 2n + 1 and 2n + 2. If you are at index k and you want to follow the left subtree, set k = 2*k+1 ; if you want to follow the right subtree, set k = 2*k+2 . Continue following the same algorithm until you hit a null element in your intHeap array.

You need to go through a good tutorial.Just to give you heads up,the node will be like this

Class Node
{
   int data;//ideally should be generic.
   Node leftChild;
   Node rightChild;
   ...

}

Recommend you to visit Binary Search Tree - Java Implementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM