The Easiest Way to Save and Share Code Snippets on the web

tests for non-recursive binary tree traversal in perl6

perl

last edit: Jan, 31st 2012 | jump to bottom

  1. # written for CSC206 by Jonathan Buhacoff on 31 Jan 2012
  2. use Algorithm::BinaryTree;
  3.  
  4. sub node($value,$left?,$right?) {
  5. return BinaryTreeNode.new(value=>$value, left=>$left, right=>$right);
  6. }
  7.  
  8. # $root is the root node if a binary tree
  9. # $resultStr is the order the nodes are expected, separated by spaces. Ex: "D E B F G C A"
  10. sub test($root,$resultStr) {
  11. my @result = ();
  12. my @resultNR = ();
  13. my $tree = BinaryTreeWalker.new;
  14. my $treeNR = NonRecursiveBinaryTreeWalker.new;
  15. $tree.traversePostOrder($root, -> $x { @result.push($x.value); } );
  16. $treeNR.traversePostOrder($root, -> $x { @resultNR.push($x.value); } );
  17. say "ok: $resultStr" if "{@result}" eq "{@resultNR}" eq $resultStr;
  18. }
  19.  
  20. my $balancedTree3 = node("A",
  21. node("B",
  22. node("D"),
  23. node("E")
  24. ),
  25. node("C",
  26. node("F"),
  27. node("G")
  28. )
  29. );
  30.  
  31. test($balancedTree3,"D E B F G C A");
  32.  
  33. test(Nil, "");
  34.  
  35. my $singleNode = node("A");
  36. test($singleNode, "A");
  37.  
  38. my $singleLeftLeaf = node("A",node("B"));
  39. test($singleLeftLeaf, "B A");
  40.  
  41. my $singleRightLeaf = node("A",Nil,node("C"));
  42. test($singleRightLeaf, "C A");
  43.  
  44. my $balancedHeight2 = node("A",node("B"),node("C"));
  45. test($balancedHeight2, "C B A");
  46.  
  47. my $longLeftOnlyBranch = node("A",node("B",node("C",node("D",node("E")))));
  48. test($longLeftOnlyBranch, "E D C B A");
  49.  
  50. my $longRightOnlyBranch = node("A",Nil,node("B",Nil,node("C",Nil,node("D",Nil,node("E")))));
  51. test($longRightOnlyBranch, "E D C B A");
  52.  
  53. my $slightlyRightThenLeftBranch = node("A",Nil,node("B",node("C",node("D",node("E")))));
  54. test($slightlyRightThenLeftBranch, "E D C B A");
  55.  
  56. my $slightlyLeftThenRightBranch = node("A",node("B",Nil,node("C",Nil,node("D",Nil,node("E")))));
  57. test($slightlyLeftThenRightBranch, "E D C B A");
  58.  
  59. my $waveBranch = node("A",node("B",Nil,node("C",node("D",Nil,node("E")))));
  60. test($waveBranch, "E D C B A");
  61.  
24 views