简体   繁体   中英

How can I get the root of a binary tree (set or map)?

How can I get the root node of an std::set or std::map ? It provides function for getting the begin() and end() iterators, but I haven't seen anything in the documentation about getting the root.

You can not do that. That is why you were provided with iterators - to abstract yourself away from implementation details. Moreover, I have just done Ctrl + F on "tree" keyword in C++ Standard and found only 5 occurrences none of which is related to set/map implementation details.

If you need root of binary tree - create your own data structure.

There is no concept of root node in any of those Abstract Data Types (neither set nor map ). The fact that they are implemented as a red–black tree is just an implementation detail.

Here are the operations supported:

From the wikipedia page, one of the benefits about ADT is:

Encapsulation
Abstraction provides a promise that any implementation of the ADT has certain properties and abilities; knowing these is all that is required to make use of an ADT object. The user does not need any technical knowledge of how the implementation works to use the ADT. In this way, the implementation may be complex but will be encapsulated in a simple interface when it is actually used.

It seems you are trying to break that encapsulation trying to know too much about the implementation.

I was also looking at this functionality. Looks like we can't directly get the root value of an stl map or set unless we iterate thru the map/set.

Ex: from the total size of the map, get the root index (which is size/2) and then iterate till you have covered that many elements in the map. THis approach will work since the stl map is internally a balanced tree.

Why I need this?

For a problem, I want to get the median. The easiest way out is to return the root (or the average of root and its right child).

I also have my own implementation of a binary tree which I could use here. But for this problem, I want the tree to be balanced.

I have the following options -

  1. use a stl map. This is a balanced DS. however, there is no easy way of getting the root or an element by index number. Ex: I can't get the element at index 4. So, I was thinking of iterating thru the map till I get the root. Nice and quick and easy - but calculating the median will take O(n/2).

  2. Implement a balanced tree and add a function to return the root value. More work to do. However, I can retrieve the median in O(1) time.

If you can think of a better way to do this, pls let me know.

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