简体   繁体   中英

What are some algorithms for incrementally building a balanced binary tree with no order constraints?

I am interested in taking a list of elements and turning them into a balanced binary tree with each element on a leaf of the tree. Furthermore, I want to build the tree with an algorithm that only sees one element at a time, rather than the whole list at once. Finally, this tree has no ordering constraints --- that is, it is not a search tree, so the nodes can be in any order.

My question is: there are lots of algorithms for incrementally building up binary search trees, but what are some algoritms for building up balanced binary trees without any ordering constraint? They ought to be more efficient as they don't have to worry about preserving any order relations between the nodes.

You can do it in linear time. For each 2 elements, you need a parent. For each 2 of those, you need another and so on. Can't do it any better though.

First you make N nodes for each data point you have - then you just start working your way back up - connect each two leafs together with a node, then each 2 of those parent nodes together, etc, until you get to 1 node.

Or you can work your way down -- at any level N you get 2^N children.

nodes = [...data...]

root = data.first; <== returns first element without removing it from nodes
while data.size > 1
  a=data.pop_front
  b=data.pop_front

  root = new node(a,b) <== create new node with a and b as children
  data.push_back(root) 

when you leave the while loop, root contains the top of your tree.

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