


Detailed explanation of the steps of binary tree depth and breadth first traversal algorithm in PHP
This time I will bring you a detailed explanation of the algorithm steps for implementing depth and breadth-first traversal of binary trees in PHP. What are the precautions for implementing depth and breadth-first traversal of binary trees in PHP. Here are practical cases. Let’s take a look. .
Foreword:
Depth-first traversal: Go deep into every possible branch path until it can no longer go deeper. And each node can only be visited once. It is important to note that the depth-first traversal of a binary tree is special and can be subdivided into pre-order traversal, in-order traversal, and post-order traversal. The specific instructions are as follows:
Pre-order traversal: root node->left subtree->right subtree
In-order traversal: left subtree->root node->right subtree
Post-order traversal: left subtree->right subtree->root node
Breadth-first traversal: Also called hierarchical traversal, each layer is traversed from top to bottom. Access, in each layer, access nodes from left to right (or right to left). After accessing one layer, enter the next layer until no nodes can be accessed.
For example, for this tree:
Depth-first traversal:
Preorder traversal: 10 8 7 9 12 11 13
In-order traversal: 7 8 9 10 11 12 13
Post-order traversal: 7 9 8 11 13 12 10
Breadth-first traversal:
Level traversal: 10 8 12 7 9 11 13
The common non-recursive method of depth-first traversal of a binary tree is to use a stack, and the common non-recursive method of breadth-first traversal is to use a queue.
Depth first traversal:
1. Preorder traversal:
/** * 前序遍历(递归方法) */ private function pre_order1($root) { if (!is_null($root)) { //这里用到常量FUNCTION,获取当前函数名,好处是假如修改函数名的时候,里面的实现不用修改 $function = FUNCTION; echo $root->key . " "; $this->$function($root->left); $this->$function($root->right); } } /** * 前序遍历(非递归方法) * 因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。 */ private function pre_order2($root) { // $stack = new splstack(); // $stack->push($root); // while(!$stack->isEmpty()){ // $node = $stack->pop(); // echo $node->key.' '; // if(!is_null($node->right)){ // $stack->push($node->right); // } // if(!is_null($node->left)){ // $stack->push($node->left); // } // } if (is_null($root)) { return; } $stack = new splstack(); $node = $root; while (!is_null($node) || !$stack->isEmpty()) { while (!is_null($node)) { //只要结点不为空就应该入栈保存,与其左右结点无关 $stack->push($node); echo $node->key . ' '; $node = $node->left; } $node = $stack->pop(); $node = $node->right; } } //前序遍历 public function PreOrder() { // 所在对象中的tree属性保存了一个树的引用 // $this->pre_order1($this->tree->root); $this->pre_order2($this->tree->root); }
Explanation: 1. I will traverse all The methods are all encapsulated in a class traverse. 2. In the pre_order2 method, when using the stack, I use splstack provided by the PHP standard library SPL. If you are used to using arrays, you can use <a href="http://www.php.cn/wiki/1001.html" target="_blank">array_push</a>()
and array_pop()
Simulation implementation.
2. In-order traversal:
/** * 中序遍历(递归方法) */ private function mid_order1($root) { if (!is_null($root)) { $function = FUNCTION; $this->$function($root->left); echo $root->key . " "; $this->$function($root->right); } } /** * 中序遍历(非递归方法) * 因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。 */ private function mid_order2($root) { if (is_null($root)) { return; } $stack = new splstack(); $node = $root; while (!is_null($node) || !$stack->isEmpty()) { while (!is_null($node)) { $stack->push($node); $node = $node->left; } $node = $stack->pop(); echo $node->key . ' '; $node = $node->right; } } //中序遍历 public function MidOrder() { // $this->mid_order1($this->tree->root); $this->mid_order2($this->tree->root); }
3. Post-order traversal:
/** * 后序遍历(递归方法) */ private function post_order1($root) { if (!is_null($root)) { $function = FUNCTION; $this->$function($root->left); $this->$function($root->right); echo $root->key . " "; } } /** * 后序遍历(非递归方法) * 因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。 * 由于在访问了左子节点后怎么跳到右子节点是难点,这里使用一个标识lastVisited来标识上一次访问的结点 */ private function post_order2($root) { if (is_null($root)) { return; } $node = $root; $stack = new splstack(); //保存上一次访问的结点引用 $lastVisited = NULL; $stack->push($node); while(!$stack->isEmpty()){ $node = $stack->top();//获取栈顶元素但不弹出 if(($node->left == NULL && $node->right == NULL) || ($node->right == NULL && $lastVisited == $node->left) || ($lastVisited == $node->right)){ echo $node->key.' '; $lastVisited = $node; $stack->pop(); }else{ if($node->right){ $stack->push($node->right); } if($node->left){ $stack->push($node->left); } } } } //后序遍历 public function PostOrder() { // $this->post_order1($this->tree->root); $this->post_order2($this->tree->root); }
Breadth-first traversal:
1. Level traversal:
/** * 层次遍历(递归方法) * 由于是按层逐层遍历,因此传递树的层数 */ private function level_order1($root,$level){ if($root == NULL || $level < 1){ return; } if($level == 1){ echo $root->key.' '; return; } if(!is_null($root->left)){ $this->level_order1($root->left,$level - 1); } if(!is_null($root->right)){ $this->level_order1($root->right,$level - 1); } } /** * 层次遍历(非递归方法) * 每一层从左向右输出 元素需要储存有先进先出的特性,所以选用队列存储。 */ private function level_order2($root){ if(is_null($root)){ return; } $node = $root; //利用队列实现 // $queue = array(); // array_push($queue,$node); // // while(!is_null($node = array_shift($queue))){ // echo $node->key.' '; // if(!is_null($node->left)){ // array_push($queue,$node->left); // } // if(!is_null($node->right)){ // array_push($queue,$node->right); // } // } $queue = new splqueue(); $queue->enqueue($node); while(!$queue->isEmpty()){ $node = $queue->dequeue(); echo $node->key.' '; if (!is_null($node->left)) { $queue->enqueue($node->left); } if (!is_null($node->right)) { $queue->enqueue($node->right); } } } //层次遍历 public function LevelOrder(){ // $level = $this->getdepth($this->tree->root); // for($i = 1;$i <= $level;$i ++){ // $this->level_order1($this->tree->root,$i); // } $this->level_order2($this->tree->root); } //获取树的层数 private function getdepth($root){ if(is_null($root)){ return 0; } $left = getdepth($root -> left); $right = getdepth($root -> right); $depth = ($left > $right ? $left : $right) + 1; return $depth; }
Description: In the level_order2 method, when using the queue, I use the splqueue provided by the PHP standard library SPL. If you are used to using arrays, you can use array_push()
and array_shift()
Simulation implementation.
Usage:
Now let’s look at the client code:
class Client { public static function Main() { try { //实现文件的自动加载 function autoload($class) { include strtolower($class) . '.php'; } spl_autoload_register('autoload'); $arr = array(10, 8, 12, 7, 9, 11, 13); $tree = new Bst(); // $tree = new Avl(); // $tree = new Rbt(); $tree->init($arr); $traverse = new traverse($tree); $traverse->PreOrder(); // $traverse->MidOrder(); // $traverse->PostOrder(); // $traverse->LevelOrder(); } catch (Exception $e) { echo $e->getMessage(); } } } CLient::Main();
Supplementary:
1. For the three classes Bst, Avl, and Rbt used in the client, you can refer to the previous article: "Detailed explanation of the graphic display function of drawing binary trees in PHP"
2. Why do I recommend that you use splstack
and splqueue
provided in the SPL standard library? This is what I saw in an article: Although we can use traditional variable types to describe data structures, such as using arrays to describe stacks (Strack) - then use the corresponding methods pop and push (array_pop( )
, array_push()
), but you have to be careful, because after all, they are not specifically designed to describe data structures – one wrong operation may destroy the stack. SPL's SplStack object strictly describes data in the form of a stack and provides corresponding methods. At the same time, such code should also be able to understand that it is operating on a stack rather than an array, allowing your peers to better understand the corresponding code, and it will be faster. Original address: PHP SPL, the lost gem
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Detailed explanation of PHP simple selection sorting case
Detailed explanation of the steps to implement Huffman encoding/decoding in PHP
The above is the detailed content of Detailed explanation of the steps of binary tree depth and breadth first traversal algorithm in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
