This article mainly introduces PHP implementation of the construction of two-fork tree algorithm, interested in the reference of friends, I hope to be helpful to everyone.
The tree is still important in the data structure, which means that the binary tree is represented by parentheses. Write a binary tree node class first:
Binary tree node class Btnode {public $data; Public $lchild = NULL; Public $rchild = NULL; Public function __construct ($data) { $this->data = $data; }}
Then construct a two-fork tree:
Function Createbtnode (& $root, String $str) { $STRARR = Str_split ($STR); $stack = []; $p = NULL; Pointer $top =-1; $k = $j = 0; $root = NULL; foreach ($strArr as $ch) { switch ($ch) {case ' (': $top + +; Array_push ($stack, $p); $k = 1; break; Case ') ': array_pop ($stack); break; Case ', ': $k = 2; break; Default: $p = new Btnode ($ch); if ($root = = NULL) { $root = $p; } else { switch ($k) {case 1: End ($stack)->lchild = $p; break; Case 2: end ($stack)->rchild = $p; break; } } Break;}}}
Here is a function to print a binary tree (middle sequence traversal):
function Printbtnode ($node) { if ($node! = NULL) { printbtnode ($node->lchild); echo $node->data; Printbtnode ($node->rchild);} }
Operation Result:
Enter a string
"A (B (c,d), G (F))"