The central traversal of a binary tree assumes that 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. I have already implemented the pre-order traversal. now I want to traverse this binary tree in the middle order. I hope you can provide a good method. // Binary tree structure $ array = array ("-", array ("+", array ("a"), array ("*", array ("B "), central traversal of ar binary tree
Assume that the binary tree structure 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. I have already implemented the pre-order traversal. now I want to traverse this binary tree in the middle order. I hope you can provide 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, hope you can recommend it)
------ Solution --------------------
The binary tree you provided is not strictly represented. each node should be represented by an associated array instead of a subscript array.
Fortunately, your tree is full, otherwise it is easy to misunderstand
The subscript of each node represents
0 root 1 left child 2 right child
Defined by binary tree traversal.
/* Forward 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]);
}
/* Sequential 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-order 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];
}
Preface-+ a * B-cd/ef
Central order a + B * c-d-e/f
Back-order abcd-* + ef /-