PHP implementation method of constructing two-fork tree algorithm

Source: Internet
Author: User
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))"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.