The previous time has been looking at the algorithm problem, now the results of the study posted.
1. Build a common binary tree
<?phpclass Node {public $value = 0; public $l = null; Public $r = null;};/ /build Tree function Buildtree ($a, $low, $high) { if ($low > $high) { return null; } $m = Floor (($low + $high)/2); $node = new node; $node->value = $a [$m]; $l = Buildtree ($a, $low, $m-1); $r = Buildtree ($a, $m +1, $high); $node->l = $l; $node->r = $r; return $node;}
2. Establish an ordered binary tree
<?phpclass Node {public $value = 0; public $l = null; Public $r = null;};/ /ordered binary tree function insertordertree ($T, $value) { if ($T->value = = $value) { return; } if ($T->value > $value) { if ($T->l = = = null) { $node = new node (); $node->value = $value; $T->l = $node; } else { Insertordertree ($T->l, $value), } } else { if ($T->r = = null) { $node = new node (); $node->value = $value; $T->r = $node; } else { Insertordertree ($T->r, $value);}}} function Buildordertree ($seq) { $R = new Node (); $R->value = 5; foreach ($seq as $value) { insertordertree ($R, $value); } return $R;}
3. Traversal of a two-fork tree
Middle order traversal function travel ($T) { if ($T = = null) { return; } echo $T->value, "\ n"; Travel ($T->l); Travel ($T->r);} First Order traversal function Intravel ($T) { if ($T = = null) { return; } Intravel ($T->l); echo $T->value, "\ n"; Intravel ($T->r);} Post-Traversal function Posttravel ($T) { if ($T = = null) { return; } Posttravel ($T->l); Posttravel ($T->r); echo $T->value, "\ n";} Hierarchy traversal function Leveltravel ($T) { $q = array (); Array_push ($q, $T); while (!empty ($q)) { $node = Array_shift ($q); if ($node->l) { Array_push ($q, $node->l); } if ($node->r) { Array_push ($q, $node->r); } echo $node->value, "\ n"; }}
Binary Tree Setup record (PHP implementation)