Home > Backend Development > PHP Tutorial > PHP binary tree construction algorithm sample code

PHP binary tree construction algorithm sample code

怪我咯
Release: 2023-03-12 18:18:01
Original
1639 people have browsed it

This article mainly introduces examples of binary tree construction algorithm in PHP. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

Tree is still very important in the data structure. Here, the binary tree is represented by bracket notation. First write a binary tree node class:

// 二叉树节点
class BTNode {
  public $data;

  public $lchild = NULL;

  public $rchild = NULL;

  public function construct($data) {
    $this->data = $data;
  }
}
Copy after login

Then construct the binary tree:

function CreateBTNode(&$root,string $str)
{
  $strArr = str_split($str);
  $stack = [];
  $p = NULL; // 指针
  $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;
    }
  }
}
Copy after login

Write a function to print the binary tree here (in-order traversal):

function PrintBTNode($node)
{
  if($node != NULL) {
    PrintBTNode($node->lchild);
    echo $node->data;
    PrintBTNode($node->rchild);
  }
}
Copy after login

Running result:

Enter a string
"A(B(C,D),G(F))"

The above is the detailed content of PHP binary tree construction algorithm sample code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template