前段时间一直在看算法问题,现在把研究的结果贴出来。
1.建立普通二叉树
<?php class Node { public $value = 0; public $l = null; public $r = null; }; //构建树 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.建立有序二叉树
<?php class Node { public $value = 0; public $l = null; public $r = null; }; // 有序二叉树 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.对二叉树的遍历
// 中序遍历 function travel($T) { if ($T == null) { return; } echo $T->value, "\n"; travel($T->l); travel($T->r); } // 先序遍历 function inTravel($T) { if ($T == null) { return; } inTravel($T->l); echo $T->value, "\n"; inTravel($T->r); } //后序遍历 function postTravel($T) { if ($T == null) { return; } postTravel($T->l); postTravel($T->r); echo $T->value, "\n"; } // 层级遍历 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"; } }
时间: 2024-12-28 08:42:21