The middle sequence traversal of binary tree
Suppose the structure of the binary tree is the following array, the array subscript 0 is the root node, 1 is the left child node, and 2 is the right child node. The pre-sequence traversal I have realized, now I want to be able to traverse this binary tree in sequence, I hope you give a good method.
Binary tree structure
$array =array ("-", Array ("+", Array ("a"), Array ("*", Array ("B"), Array ("-", Array ("C"), Array ("D"))), Array ("/", Array ( "E"), Array ("F")));
echo "";
Print_r ($array);
echo "
";
Pre-order Traversal code
function Bianli ($array) {
foreach ($array as $value) {
if (Is_array ($value)) {
Bianli ($value);
}else{
Echo $value;
}
}
}
echo Bianli ($array);
PS (another to download the English academic paper website, bi set English translation needs to use, I find from the Google Academic PDF version is not clear, do not know if there are no other sites can be downloaded, I hope you can recommend)
------Solution--------------------
The two-fork tree you give is not very tight, and each node should be represented by an associative array rather than an array of subscripts.
Fortunately, your tree is full, otherwise it's very easy to misunderstand.
The subscript for each of your nodes is indicated separately
0 Root 1 Left child 2 right child
Defined by a two-fork tree traversal, there are
/* Pre-sequence traversal */
function DLR ($F) {
if (isset ($F [0])) echo $F [0];
if (Isset ($F [1])) DLR ($F [1]);
if (Isset ($F [2])) DLR ($F [2]);
}
/* Middle Sequence traversal */
function LDR ($F) {
if (Isset ($F [1]) LDR ($F [1]);
if (isset ($F [0])) echo $F [0];
if (Isset ($F [2]) LDR ($F [2]);
}
/* post-traversal */
function LRD ($F) {
if (Isset ($F [1])) LRD ($F [1]);
if (Isset ($F [2])) LRD ($F [2]);
if (isset ($F [0])) echo $F [0];
}
Pre-order-+a*b-cd/ef
Middle order a+b*c-d-e/f
Post abcd-*+ef/-