1. 云栖社区>
  2. PHP教程>
  3. 正文

PHP的各种遍历

作者:用户 来源:互联网 时间:2017-12-01 15:44:46

PHP的各种遍历 - 摘要: 本文讲的是PHP的各种遍历, <?php#二叉树的非递归遍历class Node { public $data; public $left; public $right;}#前序遍历,和深度遍历一样function preorder($root) { $stac

<?php#二叉树的非递归遍历class Node {	public $data;	public $left;	public $right;}#前序遍历,和深度遍历一样function preorder($root) {	$stack = array ();	array_push ( $stack, $root );	while ( ! empty ( $stack ) ) {		$cnode = array_pop ( $stack );		echo $cnode->data . " ";		if ($cnode->right != null)			array_push ( $stack, $cnode->right );		if ($cnode->left != null)			array_push ( $stack, $cnode->left );	}}#中序遍历function inorder($root) {	$stack = array ();	$cnode = $root;	while ( ! empty ( $stack ) || $cnode != null ) {		while ( $cnode != null ) {			array_push ( $stack, $cnode );			$cnode = $cnode->left;		}		$cnode = array_pop ( $stack );		echo $cnode->data . " ";				$cnode = $cnode->right;	}}#后序遍历#使用双栈实现function postorder($root) {	$pushstack = array ();	$visitstack = array ();	array_push ( $pushstack, $root );		while ( ! empty ( $pushstack ) ) {		$cnode = array_pop ( $pushstack );		array_push ( $visitstack, $cnode );		if ($cnode->left != null)			array_push ( $pushstack, $cnode->left );		if ($cnode->right != null)			array_push ( $pushstack, $cnode->right );	}		while ( ! empty ( $visitstack ) ) {		$cnode = array_pop ( $visitstack );		echo $cnode->data . " ";	}}$root = new Node ();$n1 = new Node ();$n11 = new Node ();$n12 = new Node ();$n2 = new Node ();$n21 = new Node ();$n22 = new Node ();$n111 = new Node ();$n112 = new Node ();$root->data = 0;$n1->data = 1;$n11->data = 11;$n111->data = 111;$n112->data = 112;$n12->data = 12;$n2->data = 2;$n21->data = 21;$n22->data = 22;$root->left = $n1;$root->right = $n2;$n1->left = $n11;$n1->right = $n12;$n2->left = $n21;$n2->right = $n22;$n11->left = $n111;$n11->right = $n112;preorder ( $root );echo "<br>";inorder ( $root );echo "<br>";postorder ( $root );?>

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。