Binary tree traversal algorithm
A. Binary tree traversal
1. Preorder traversal of the binary tree:
(1) If the binary tree is empty, it is a no-op operation and returns empty.
(2) Visit the root node.
(3) Preorder traversal of the left subtree.
(4) Preorder traverse the right subtree.
##a. Recursive algorithm for pre-order traversal of binary trees:
void PreOrderTraverse(BiTree BT) { if(BT) { printf("%c",BT->data); //访问根结点 PreOrderTraverse(BT->lchild); //前序遍历左子树 PreOrderTraverse(BT->rchild); //前序遍历右子树 } }
b. Non-recursive algorithm for binary tree pre-order traversal using stack to store the right subtree of each node:
( 1) When the tree is empty, point the pointer p to the root node, and p is the current node pointer.
(2) First visit the current node p and push p into the stack S.
(3) Let p point to its left child.
(4) Repeat steps (2) and (3) until p is empty.
(5) Pop the top element from stack S and point p to the right child of this element.
(6) Repeat steps (2)~(5) until p is empty and stack S is also empty.
(7) The traversal ends.
Non-recursive algorithm using pre-order traversal of the stack:
void PreOrderNoRec(BiTree BT) { stack S; BiTree p=BT->root; while((NULL!=p)||!StackEmpty(S)) { if(NULL!=p) { printf("%c",p->data); Push(S,p); p=p->lchild; } else { p=Top(S); Pop(S); p=p->rchild; } } }
c. Use binary linked list storage Non-recursive algorithm for pre-order traversal of a binary tree:
void PreOrder(pBinTreeNode pbnode) { pBinTreeNode stack[100]; pBinTreeNode p; int top; top=0; p=pbnode; do { while(p!=NULL) { printf("%d\n",p->data); //访问结点p top=top+1; stack[top]=p; p=p->llink; //继续搜索结点p的左子树 } if(top!=0) { p=stack[top]; top=top-1; p=p->rlink; //继续搜索结点p的右子树 } }while((top!=0)||(p!=NULL)); }
2. In-order traversal of a binary tree:
( 1) If the binary tree is empty, it is a no-op operation and returns empty.(2) In-order traversal of the left subtree.
(3) Visit the root node.
(4) In-order traversal of the right subtree.
void InOrderTraverse(BiTree BT) { if(BT) { InOrderTraverse(BT->lchild); //中序遍历左子树 printf("%c",BT->data); //访问根结点 InOrderTraverse(BT->rchild); //中序遍历右子树 } }
b. Non-recursive algorithm for in-order traversal of binary trees using stack storage:
(3) Repeat step (2) until p is empty.
(4) Pop the top element from stack S and point p to this element.
(5) Access the current node p and point p to its right child.
(6) Repeat steps (2)~(5) until p is empty and stack S is also empty.
(7) The traversal ends.
Non-recursive algorithm using in-order traversal of the stack:
void IneOrderNoRec(BiTree BT) { stack S; BiTree p=BT->root; while((NULL!=p)||!StackEmpty(S)) { if(NULL!=p) { Push(S,p); p=p->lchild; } else { p=Top(S); Pop(S); printf("%c",p->data); p=p->rchild; } } }
c. Use binary fork Non-recursive algorithm for in-order traversal of a binary tree stored in a linked list:
void InOrder(pBinTreeNode pbnode) { pBinTreeNode stack[100]; pBinTreeNode p; int top; top=0; p=pbnode; do { while(p!=NULL) { top=top+1; stack[top]=p; //结点p进栈 p=p->llink; //继续搜索结点p的左子树 } if(top!=0) { p=stack[top]; //结点p出栈 top=top-1; printf("%d\n",p->data); //访问结点p p=p->rlink; //继续搜索结点p的右子树 } }while((top!=0)||(p!=NULL)); }
(1) If the binary tree is empty, it is a no-op operation and returns empty.
(3) Post-order traversal of the right subtree.
(4) Visit the root node.
void PostOrderTraverse(BiTree BT) { if(BT) { PostOrderTraverse(BT->lchild); //后序遍历左子树 PostOrderTraverse(BT->rchild); //后序遍历右子树 printf("%c",BT->data); //访问根结点 } }
b.使用栈存储的二叉树后序遍历的非递归算法:
算法思想:首先扫描根结点的所有左结点并入栈,然后出栈一个结点,扫描该结点的右结点并入栈,再扫描该右结点的所有左结点并入栈,当一个结点的左、右子树均被访问后再访问该结点。因为在递归算法中,左子树和右子树都进行了返回,因此为了区分这两种情况,还需要设置一个标识栈tag,当tag的栈顶元素为0时表示从左子树返回,为1表示从右子树返回。
(1)当树为空时,将指针p指向根结点,p为当前结点指针。
(2)将p压入栈S中,0压入栈tag中,并令p指向其左孩子。
(3)重复执行步骤(2),直到p为空。
(4)如果tag栈中的栈顶元素为1,跳至步骤(6)。
(5)如果tag栈中的栈顶元素为0,跳至步骤(7)。
(6)将栈S的栈顶元素弹出,并访问此结点,跳至步骤(8)。
(7)将p指向栈S的栈顶元素的右孩子。
(8)重复执行步骤(2)~(7),直到p为空并且栈S也为空。
(9)遍历结束。
使用栈的后序遍历非递归算法:
void PostOrderNoRec(BiTree BT) { stack S; stack tag; BiTree p=BT->root; while((NULL!=p)||!StackEmpty(S)) { while(NULL!=p) { Push(S,p); Push(tag,0); p=p->lchild; } if(!StackEmpty(S)) { if(Pop(tag)==1) { p=Top(S); Pop(S); printf("%c",p->data); Pop(tag); //栈tag要与栈S同步 } else { p=Top(S); if(!StackEmpty(S)) { p=p->rchild; Pop(tag); Push(tag,1); } } } } }
c.使用二叉链表存储的二叉树后序遍历非递归算法:
void PosOrder(pBinTreeNode pbnode) { pBinTreeNode stack[100]; //结点的指针栈 int count[100]; //记录结点进栈次数的数组 pBinTreeNode p; int top; top=0; p=pbnode; do { while(p!=NULL) { top=top+1; stack[top]=p; //结点p首次进栈 count[top]=0; p=p->llink; //继续搜索结点p的左子树 } p=stack[top]; //结点p出栈 top=top-1; if(count[top+1]==0) { top=top+1; stack[top]=p; //结点p首次进栈 count[top]=1; p=p->rlink; //继续搜索结点p的右子树 } else { printf("%d\n",p->data); //访问结点p p=NULL; } }while((top>0)); }
B 线索化二叉树:

typedef struct node { DataType data; struct node *lchild, *rchild; //左、右孩子指针 int ltag, rtag; //左、右线索 }TBinTNode; //结点类型 typedef TBinTNode *TBinTree;

(1)中序线索化二叉树的算法:
void InOrderThreading(TBinTree p) { if(p) { InOrderThreading(p->lchild); //左子树线索化 if(p->lchild) p->ltag=0; else p->ltag=1; if(p->rchild) p->rtag=0; else p->rtag=1; if(*(pre)) //若*p的前驱*pre存在 { if(pre->rtag==1) pre->rchild=p; if(p->ltag==1) p->lchild=pre; } pre=p; //另pre是下一访问结点的中序前驱 InOrderThreading(p->rchild); //右子树线索化 } }
(2)在中序线索化二叉树下,结点p的后继结点有以下两种情况:
①结点p的右子树为空,那么p的右孩子指针域为右线索,直接指向结点p的后继结点。②结点p的右子树不为空,那么根据中序遍历算法,p的后继必是其右子树中第1个遍历到的结点。
TBinTNode *InOrderSuc(BiThrTree p) { TBinTNode *q; if(p->rtag==1) //第①情况 return p->rchild; else //第②情况 { q=p->rchild; while(q->ltag==0) q=q->lchild; return q; } }
中序线索化二叉树求前驱结点的算法:
TBinTNode *InOrderPre(BiThrTree p) { TBinTNode *q; if(p->ltag==1) return p->lchild; else { q=p->lchild; //从*p的左孩子开始查找 while(q->rtag==0) q=q->rchild; return q; } }
(3)遍历中序线索化二叉树的算法
void TraversInOrderThrTree(BiThrTree p) { if(p) { while(p->ltag==0) p=p->lchild; while(p) { printf("%c",p->data); p=InOrderSuc(p); } } }
For more technical articles related to common problems, please visit the FAQ column to learn!
The above is the detailed content of Binary tree traversal algorithm. 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



Written above & the author’s personal understanding: At present, in the entire autonomous driving system, the perception module plays a vital role. The autonomous vehicle driving on the road can only obtain accurate perception results through the perception module. The downstream regulation and control module in the autonomous driving system makes timely and correct judgments and behavioral decisions. Currently, cars with autonomous driving functions are usually equipped with a variety of data information sensors including surround-view camera sensors, lidar sensors, and millimeter-wave radar sensors to collect information in different modalities to achieve accurate perception tasks. The BEV perception algorithm based on pure vision is favored by the industry because of its low hardware cost and easy deployment, and its output results can be easily applied to various downstream tasks.

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

The convergence of artificial intelligence (AI) and law enforcement opens up new possibilities for crime prevention and detection. The predictive capabilities of artificial intelligence are widely used in systems such as CrimeGPT (Crime Prediction Technology) to predict criminal activities. This article explores the potential of artificial intelligence in crime prediction, its current applications, the challenges it faces, and the possible ethical implications of the technology. Artificial Intelligence and Crime Prediction: The Basics CrimeGPT uses machine learning algorithms to analyze large data sets, identifying patterns that can predict where and when crimes are likely to occur. These data sets include historical crime statistics, demographic information, economic indicators, weather patterns, and more. By identifying trends that human analysts might miss, artificial intelligence can empower law enforcement agencies

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images

Java is a popular programming language with powerful file handling capabilities. In Java, traversing a folder and getting all file names is a common operation, which can help us quickly locate and process files in a specific directory. This article will introduce how to implement a method of traversing a folder and getting all file names in Java, and provide specific code examples. 1. Use the recursive method to traverse the folder. We can use the recursive method to traverse the folder. The recursive method is a way of calling itself, which can effectively traverse the folder.

1. Background of the Construction of 58 Portraits Platform First of all, I would like to share with you the background of the construction of the 58 Portrait Platform. 1. The traditional thinking of the traditional profiling platform is no longer enough. Building a user profiling platform relies on data warehouse modeling capabilities to integrate data from multiple business lines to build accurate user portraits; it also requires data mining to understand user behavior, interests and needs, and provide algorithms. side capabilities; finally, it also needs to have data platform capabilities to efficiently store, query and share user profile data and provide profile services. The main difference between a self-built business profiling platform and a middle-office profiling platform is that the self-built profiling platform serves a single business line and can be customized on demand; the mid-office platform serves multiple business lines, has complex modeling, and provides more general capabilities. 2.58 User portraits of the background of Zhongtai portrait construction

Written above & The author’s personal understanding is that in the autonomous driving system, the perception task is a crucial component of the entire autonomous driving system. The main goal of the perception task is to enable autonomous vehicles to understand and perceive surrounding environmental elements, such as vehicles driving on the road, pedestrians on the roadside, obstacles encountered during driving, traffic signs on the road, etc., thereby helping downstream modules Make correct and reasonable decisions and actions. A vehicle with self-driving capabilities is usually equipped with different types of information collection sensors, such as surround-view camera sensors, lidar sensors, millimeter-wave radar sensors, etc., to ensure that the self-driving vehicle can accurately perceive and understand surrounding environment elements. , enabling autonomous vehicles to make correct decisions during autonomous driving. Head