深度优先遍历
class node
{
public $val;
public $leftNode;
public $rightNode;
public function __construct($val)
{
$this->val = $val;
}
}
$node5 = new node(6);
$node4 = new node(3);
$node3 = new node(5);
$node2 = new node(8);
$node1 = new node(7);
$node1->leftNode = $node3;
$node1->rightNode = $node2;
$node3->leftNode = $node4;
$node3->rightNode = $node5;
function Order($node)
{
if ($node) {
$cur = $node->val;
$left = Order($node->leftNode);
$right = Order($node->rightNode);
return $left . '-' . $cur . '-' . $right; // 中序遍历
/*
* return $cur. '-' . $left . '-' . $right; // 前序遍历
* return $left . '-' . $right . '-' . $cur; // 后序遍历
* note: 没有的子节点,return的时候注意这个'-'不要哦,我这里为了逻辑清晰就没做判断(不要在意这些细节)
*/
}
}
echo Order($node1);