Einzelnen Beitrag anzeigen

alzaimar
(Moderator)

Registriert seit: 6. Mai 2005
Ort: Berlin
4.956 Beiträge
 
Delphi 2007 Enterprise
 
#3

Re: Create Binary Tree From Preorder input

  Alt 22. Apr 2006, 10:01
Hi,

Try something like this:
Divide the list into two halves. The mid element is your root.
Now do a recursive call to create a tree out of the left sub list and return the root as the left child of the above mentioned root. Do the same with the right sub list.

Delphi-Quellcode:
Procedure CreateTree (aList : TList; aLeft, aRight : Integer; Var aRoot : TNode);
Begin
  If aLeft >= aRight Then
     aRoot := aList [aLeft]
  Else Begin
     m := (aLeft + aRight) div 2;
     aRoot := aList [m];
     if m > aLeft Then CreateTree (aList, aLeft, m - 1, aRoot.Left); // Not sure about this, you might have to test
     if m < aRight Then CreateTree (aList, m + 1, aRight, aRoot.Right);// -"-
  End
End;
One question: Why do you use something antique like a binary tree? Use Skiplists or Hashmaps for fast retrieval of keyed data, they are much much faster.
"Wenn ist das Nunstruck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput!"
(Monty Python "Joke Warefare")
  Mit Zitat antworten Zitat