# Php binary tree traversal algorithm and example-PHP source code

Source: Internet
Author: User
The binary tree algorithm is an algorithm that will be learned when learning data structures in small editors. This can improve the search performance by 50% in search and sorting, let's take a look at some php binary tree traversal algorithms and examples. The binary tree algorithm is an algorithm that will be learned when learning data structures in small editors. This can improve the search performance by 50% in search and sorting, let's take a look at some php binary tree traversal algorithms and examples.

Script ec (2); script

Binary tree traversal is a process where values start from the root node and all nodes in the binary tree are accessed in order so that each node is accessed once and only accessed according

Figure: Baidu search... Thank you for providing the map hero ..

Forward traversal of a binary tree: If the binary tree is empty, return. If the binary tree is not empty, traverse the left Tree first, then traverse the right tree, And the traversal order is ABCDEGF.

In-order binary tree traversal: If the binary tree is empty, return. If the binary tree is not empty, the left subtree of the root node is traversed from the root node, and then the root node is accessed, finally, the right subtree is traversed in the middle order, and the traversal order is CBEGDFA.

Post-sequential binary tree traversal: If the binary tree is empty, it is returned. If the binary tree is not empty, the left-to-right first leaf node access traversal accesses the Left and Right sub-trees, and finally accesses the root node. The access sequence is CGEFDBA.

Sequence traversal Binary Tree: If the binary tree is empty, return. If the binary tree is not empty, access from the first layer of the tree, that is, the root node, and traverse from top to bottom. In the same layer, access nodes one by one from left to right. The access sequence is ABCDEFG.

Now, we use PHP code to traverse the binary tree structure. A binary tree stores a large array. Each node has three fields. data indicates the value of the node. lChild indicates the left-side subnode of the node, and rChild indicates the right-side subnode of the node. The structure of the binary tree is shown in the figure above.

The binary tree structure code is as follows:

// Binary Tree

\$ Arr = array (

'Data' => 'A ',

'Lchild '=> array (

'Data' => 'B ',

'Lchild '=> array (

'Data' => 'C ',

'Lchild '=> array (),

'Rchild '=> array (),

),

'Rchild '=> array (

'Data' => 'D ',

'Lchild '=> array (

'Data' => 'E ',

'Lchild '=> array (),

'Rchild '=> array (

'Data' => 'G ',

'Lchild '=> array (),

'Rchild '=> array (),

),

),

'Rchild '=> array (

'Data' => 'F ',

'Lchild '=> array (),

'Rchild '=> array (),

),

),

),

'Rchild '=> array (),

);

Traversal Algorithm 1: traverse binary trees in the forward order

// Pre-order traversal of the Binary Tree Algorithm

Echo 'forward traversal Binary Tree Algorithm :';

PreOrderTraverse (\$ arr );

Echo'
';

Function PreOrderTraverse (\$ node ){

If (empty (\$ node )){

Return;

}

// Output value

Print_r (\$ node ['data']);

// Left Node

PreOrderTraverse (\$ node ['lchild ']);

// Right Node

PreOrderTraverse (\$ node ['rchild ']);

}

Traversal Algorithm 2: traversing a binary tree in a central order

// Median traversal Binary Tree Algorithm

Echo 'sequential traversal Binary Tree Algorithm :';

InOrderTraverse (\$ arr );

Echo'
';

Function inOrderTraverse (\$ node ){

If (empty (\$ node )){

Return;

}

// Left Node

InOrderTraverse (\$ node ['lchild ']);

// Output value

Print_r (\$ node ['data']);

// Right Node

InOrderTraverse (\$ node ['rchild ']);

}

Traversal Algorithm 3: Post-order binary tree traversal

// Post-order traversal of the Binary Tree Algorithm

Echo 'post-order traversal Binary Tree Algorithm :';

PostOrderTraverse (\$ arr );

Echo'
';

Function postOrderTraverse (\$ node ){

If (empty (\$ node )){

Return;

}

// Left Node

PostOrderTraverse (\$ node ['lchild ']);

// Right Node

PostOrderTraverse (\$ node ['rchild ']);

// Output value

Print_r (\$ node ['data']);

}

Example

/**
* Create a binary tree and perform basic operations
*
* 1. constructor: Initialize and establish a binary tree
* 2. Create a binary tree by first traversing
* 3. Traverse Binary Trees in FIFO order
* 4. Non-Recursive Algorithms for first-order traversal
* 5. traverse a binary tree in the middle order
* 6. Non-Recursive Algorithms for sequential Traversal
* 7. Traverse Binary Trees in descending order
* 8. Post-order traversal of non-Recursive Algorithms
* 9. Traverse Binary Trees in layers
* 10. Calculate the number of leaf nodes of a binary tree.
* 11. determine the depth of a binary tree
* 12. Determine whether a binary tree is an empty tree.
* 13. Empty Binary Tree
*
* @ Author xudianyang <>
* @ Version \$ Id: BinaryTree. class. php, v 1.0 13:33:00 uw Exp
*/
Header ('content-type: text/html; charset = gb2312 ');

// This class can be found in PHP implementation and basic stack operations on the Five-stack PHP data structure.

// This class can be found in the chained storage and basic operations of the queue in the PHP Data Structure 7.
Class BTNode {
// Left subtree "pointer"
Public \$ mLchild = null;
// The "Pointer" of the right subtree"
Public \$ mRchild = null;
// Node data domain
Public \$ mData = null; // The left flag field. If it is set to 1, the mLchild points to the left child of the node. If it is set to 2, The mLchild points to the node and directly advances to the node.
Public \$ intLeftTag = null;
// Indicates the right flag domain. If the value is 1, mRchild points to the right child of the node. If the value is 2, The mRchild points to the node and then directly goes to the node.
Public \$ intRightTag = null;
}
Class BinaryTree {
// Root Node
Public \$ mRoot;
// Traverse the input binary tree data in sequence
Public \$ mPBTdata = null;
/**
* Constructor: Initialize and establish a binary tree
*
* @ Param array \$ btdata first traverses the data of the input binary tree, which is a one-dimensional array. Each element represents a node value of the binary tree, and the expanded node value is ''[string with a length of 0]
* @ Return void
*/
Public function _ construct (\$ btdata = array ()){
\$ This-> mPBTdata = \$ btdata;
\$ This-> mRoot = null;
\$ This-> getPreorderTraversalCreate (\$ this-> mRoot );
}
/**
* Create a binary tree by first traversing
*
* @ Param BTNode: Binary Tree node, transmitted by reference
* @ Return void
*/
Public function getPreorderTraversalCreate (& \$ btnode ){
\$ Elem = array_shift (\$ this-> mPBTdata );
If (\$ elem = ''){
\$ Btnode = null;
} Else if (\$ elem === null ){
Return;
} Else {
\$ Btnode = new BTNode ();
\$ Btnode-> mData = \$ elem;
\$ This-> getPreorderTraversalCreate (\$ btnode-> mLchild );
\$ This-> getPreorderTraversalCreate (\$ btnode-> mRchild );
}
}
/**
* Determines whether a binary tree is empty.
*
* @ Return boolean returns true if the binary tree is not empty; otherwise, false is returned.
**/
Public function getIsEmpty (){
If (\$ this-> mRoot instanceof BTNode ){
Return false;
} Else {
Return true;
}
}
/**
* Leave the binary tree empty.
*
* @ Return void
*/
Public function setBinaryTreeNull (){
\$ This-> mRoot = null;
}
/**
* Traverse a binary tree in ascending order
*
* @ Param BTNode \$ Root Node during rootnode Traversal
* @ Param array \$ btarr: array variable of the received value, passed as reference
* @ Return void
*/
Public function getPreorderTraversal (\$ rootnode, & \$ btarr ){
If (\$ rootnode! = Null ){
\$ Btarr [] = \$ rootnode-> mData;
\$ This-> getPreorderTraversal (\$ rootnode-> mLchild, \$ btarr );
\$ This-> getPreorderTraversal (\$ rootnode-> mRchild, \$ btarr );
}
}
/**
* Non-recursive algorithm for first-order traversal
*
* @ Param BTNode \$ objRootNode Binary Tree Root Node
* @ Param array \$ array variable of the value received by arrBTdata, passed as reference
* @ Return void
*/
Public function getPreorderTraversalNoRecursion (\$ objRootNode, & \$ arrBTdata ){
If (\$ objRootNode instanceof BTNode ){
\$ ObjNode = \$ objRootNode;
\$ ObjStack = new StackLinked ();
Do {
\$ ArrBTdata [] = \$ objNode-> mData;
\$ ObjRNode = \$ objNode-> mRchild;
If (\$ objRNode! = Null ){
\$ ObjStack-> getPushStack (\$ objRNode );
}
\$ ObjNode = \$ objNode-> mLchild;
If (\$ objNode = null ){
\$ ObjStack-> getPopStack (\$ objNode );
}
} While (\$ objNode! = Null );
} Else {
\$ ArrBTdata = array ();
}
}
/**
* Traversing a binary tree in a central order
*
* @ Param BTNode \$ root node in the objRootNode Process
* @ Param array \$ array variable of the value received by arrBTdata, passed as reference
* @ Return void
*/
Public function getInorderTraversal (\$ objRootNode, & \$ arrBTdata ){
If (\$ objRootNode! = Null ){
\$ This-> getInorderTraversal (\$ objRootNode-> mLchild, \$ arrBTdata );
\$ ArrBTdata [] = \$ objRootNode-> mData;
\$ This-> getInorderTraversal (\$ objRootNode-> mRchild, \$ arrBTdata );
}
}
/**
* Non-recursive algorithm for sequential Traversal
*
* @ Param BTNode \$ objRootNode Binary Tree Root Node
* @ Param array \$ array variable of the value received by arrBTdata, passed as reference
* @ Return void
*/
Public function getInorderTraversalNoRecursion (\$ objRootNode, & \$ arrBTdata ){
If (\$ objRootNode instanceof BTNode ){
\$ ObjNode = \$ objRootNode;
\$ ObjStack = new StackLinked ();
// Traverse the left subtree and access the root node in the middle order
Do {
While (\$ objNode! = Null ){
\$ ObjStack-> getPushStack (\$ objNode );
\$ ObjNode = \$ objNode-> mLchild;
}
\$ ObjStack-> getPopStack (\$ objNode );
\$ ArrBTdata [] = \$ objNode-> mData;
\$ ObjNode = \$ objNode-> mRchild;
} While (! \$ ObjStack-> getIsEmpty ());
// Traverse the right subtree in the middle order
Do {
While (\$ objNode! = Null ){
\$ ObjStack-> getPushStack (\$ objNode );
\$ ObjNode = \$ objNode-> mLchild;
}
\$ ObjStack-> getPopStack (\$ objNode );
\$ ArrBTdata [] = \$ objNode-> mData;
\$ ObjNode = \$ objNode-> mRchild;
} While (! \$ ObjStack-> getIsEmpty ());
} Else {
\$ ArrBTdata = array ();
}
}
/**
* Post-order traversal of Binary Trees
*
* @ Param BTNode \$ Root Node during objRootNode Traversal
* @ Param array \$ array variable of the value received by arrBTdata, passed by reference
* @ Return void
*/
Public function getPostorderTraversal (\$ objRootNode, & \$ arrBTdata ){
If (\$ objRootNode! = Null ){
\$ This-> getPostorderTraversal (\$ objRootNode-> mLchild, \$ arrBTdata );
\$ This-> getPostorderTraversal (\$ objRootNode-> mRchild, \$ arrBTdata );
\$ ArrBTdata [] = \$ objRootNode-> mData;
}
}
/**
* Post-order traversal of non-Recursive Algorithms
*
BTNode \$ objRootNode Binary Tree Root Node
Array \$ arrBTdata: the array variable of the received value, transmitted as a reference
Void
*/
Public function getPostorderTraversalNoRecursion (\$ objRootNode, & \$ arrBTdata ){
If (\$ objRootNode instanceof BTNode ){
\$ ObjNode = \$ objRootNode;
\$ ObjStack = new StackLinked ();
\$ ObjTagStack = new StackLinked ();
\$ Tag = 1;
Do {
While (\$ objNode! = Null ){
\$ ObjStack-> getPushStack (\$ objNode );
\$ ObjTagStack-> getPushStack (1 );
\$ ObjNode = \$ objNode-> mLchild;
}
\$ ObjTagStack-> getPopStack (\$ tag );
\$ ObjTagStack-> getPushStack (\$ tag );
If (\$ tag = 1 ){
\$ ObjStack-> getPopStack (\$ objNode );
\$ ObjStack-> getPushStack (\$ objNode );
\$ ObjNode = \$ objNode-> mRchild;
\$ ObjTagStack-> getPopStack (\$ tag );
\$ ObjTagStack-> getPushStack (2 );

} Else {
\$ ObjStack-> getPopStack (\$ objNode );
\$ ArrBTdata [] = \$ objNode-> mData;
\$ ObjTagStack-> getPopStack (\$ tag );
\$ ObjNode = null;
}
} While (! \$ ObjStack-> getIsEmpty ());
} Else {
\$ ArrBTdata = array ();
}
}
/**
* Layered traversal of Binary Trees
*
* @ Param BTNode \$ objRootNode Binary Tree Root Node
* @ Param array \$ array variable of the value received by arrBTdata, passed as reference
* @ Return void
*/
Public function getLevelorderTraversal (\$ objRootNode, & \$ arrBTdata ){
If (\$ objRootNode instanceof BTNode ){
\$ ObjNode = \$ objRootNode;
\$ ObjQueue = new QueueLinked ();
\$ ObjQueue-> getInsertElem (\$ objNode );
While (! \$ ObjQueue-> getIsEmpty ()){
\$ ObjQueue-> getDeleteElem (\$ objNode );
\$ ArrBTdata [] = \$ objNode-> mData;
If (\$ objNode-> mLchild! = Null ){
\$ ObjQueue-> getInsertElem (\$ objNode-> mLchild );
}
If (\$ objNode-> mRchild! = Null ){
\$ ObjQueue-> getInsertElem (\$ objNode-> mRchild );
}
}
} Else {
\$ ArrBTdata = array ();
}
}
/**
* Calculate the number of leaf nodes in a binary tree.
*
* @ Param BTNode \$ objRootNode Binary Tree Root Node
* @ Return int parameter passing error returns-1
**/
Public function getLeafNodeCount (\$ objRootNode ){
If (\$ objRootNode instanceof BTNode ){
\$ IntLeafNodeCount = 0;
\$ ObjNode = \$ objRootNode;
\$ ObjStack = new StackLinked ();
Do {
If (\$ objNode-> mLchild = null & \$ objNode-> mRchild = null ){
\$ IntLeafNodeCount ++;
}
\$ ObjRNode = \$ objNode-> mRchild;
If (\$ objRNode! = Null ){
\$ ObjStack-> getPushStack (\$ objRNode );
}
\$ ObjNode = \$ objNode-> mLchild;
If (\$ objNode = null ){
\$ ObjStack-> getPopStack (\$ objNode );
}
} While (\$ objNode! = Null );
Return \$ intLeafNodeCount;
} Else {
Return-1;
}
}
/**
* Calculate the depth of a binary tree
*
* @ Param BTNode \$ objRootNode Binary Tree Root Node
* @ Return int parameter passing error returns-1
*/
Public function getBinaryTreeDepth (\$ objRootNode ){
If (\$ objRootNode instanceof BTNode ){
\$ ObjNode = \$ objRootNode;
\$ ObjQueue = new QueueLinked ();
\$ IntBinaryTreeDepth = 0;
\$ ObjQueue-> getInsertElem (\$ objNode );
\$ ObjLevel = \$ objNode;
While (! \$ ObjQueue-> getIsEmpty ()){
\$ ObjQueue-> getDeleteElem (\$ objNode );
If (\$ objNode-> mLchild! = Null ){
\$ ObjQueue-> getInsertElem (\$ objNode-> mLchild );
}
If (\$ objNode-> mRchild! = Null ){
\$ ObjQueue-> getInsertElem (\$ objNode-> mRchild );
}
If (\$ objLevel = \$ objNode ){
\$ IntBinaryTreeDepth ++;
\$ ObjLevel = @ \$ objQueue-> mRear-> mElem;
}
}
Return \$ intBinaryTreeDepth;
} Else {
Return-1;
}
}
}
Echo"

`";\$ Bt = new BinaryTree (array ('A', 'B', 'D', '','', 'E', 'E ','', '', 'C', 'F ','','',''));Echo "binary tree structure: \ r \ n ";Var_dump (\$ bt );\$ Btarr = array ();Echo "first-order recursive traversal of Binary Trees: \ r \ n ";\$ Bt-> getPreorderTraversal (\$ bt-> mRoot, \$ btarr );Var_dump (\$ btarr );Echo "first-order non-recursive traversal of a binary tree: \ r \ n ";\$ ArrBTdata = array ();\$ Bt-> getPreorderTraversalNoRecursion (\$ bt-> mRoot, \$ arrBTdata );Var_dump (\$ arrBTdata );Echo "recursive traversal of binary tree in the middle order: \ r \ n ";\$ ArrBTdata = array ();\$ Bt-> getInorderTraversal (\$ bt-> mRoot, \$ arrBTdata );Var_dump (\$ arrBTdata );Echo "non-recursive traversal of binary tree in the middle order: \ r \ n ";\$ ArrBTdata = array ();\$ Bt-> getInorderTraversalNoRecursion (\$ bt-> mRoot, \$ arrBTdata );Var_dump (\$ arrBTdata );Echo "recursive binary tree traversal in descending order: \ r \ n ";\$ ArrBTdata = array ();\$ Bt-> getPostorderTraversal (\$ bt-> mRoot, \$ arrBTdata );Var_dump (\$ arrBTdata );Echo "suborder non-recursive traversal of Binary Tree: \ r \ n ";\$ ArrBTdata = array ();\$ Bt-> getPostorderTraversalNoRecursion (\$ bt-> mRoot, \$ arrBTdata );Var_dump (\$ arrBTdata );Echo "traverse Binary Tree by hierarchy: \ r \ n ";\$ ArrBTdata = array ();\$ Bt-> getLevelorderTraversal (\$ bt-> mRoot, \$ arrBTdata );Var_dump (\$ arrBTdata );Echo "the number of leaf nodes is:". \$ bt-> getLeafNodeCount (\$ bt-> mRoot );Echo "\ r \ n ";Echo "binary tree depth:". \$ bt-> getBinaryTreeDepth (\$ bt-> mRoot );Echo "\ r \ n ";Echo "judge whether the binary tree is empty :";Var_dump (\$ bt-> getIsEmpty ());Echo "leave the binary tree empty :";\$ Bt-> setBinaryTreeNull ();Var_dump (\$ bt );Echo"`
";
?>
Related Keywords:

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.