C++程序实现给定二叉树的后序递归遍历
树遍历是图遍历的一种形式。它涉及到精确检查或打印树中的每个节点一次。二叉搜索树的后序遍历涉及按照(左、右、根)的顺序访问树中的每个节点。
二叉树的后序遍历示例如下。
给定如下二叉树。

后序遍历结果为:1 5 4 8 6
执行后序递归遍历的程序如下所示。
示例
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"Post-Order traversal of the Binary Search Tree is: ";
postorder(root);
return 0;
}输出
Post-Order traversal of the Binary Search Tree is: 1 3 2 9 5 4
在上面的程序中,结构体node创建树的节点。该结构体是一个自引用结构体,因为它包含struct node类型的指针。该结构体显示如下。
struct node {
int data;
struct node *left;
struct node *right;
};函数createNode()创建一个节点temp并使用malloc为其分配内存。数据值val存储在temp的data中。NULL存储在temp的left和right指针中。这可以通过以下代码片段演示。
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}函数postorder()以二叉树的根节点作为参数,并以后序方式打印树的元素。它是一个递归函数。它使用以下代码进行演示。
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
}函数insertNode()将所需的值插入到二叉树的正确位置。如果节点为NULL,则调用createNode。否则,在树中找到节点的正确位置。这可以在以下代码片段中观察到。
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}在main()函数中,首先将根节点定义为NULL。然后将所有具有所需值的节点插入到二叉搜索树中。如下所示。
struct node *root = NULL; root = insertNode(root, 4); insertNode(root, 5); insertNode(root, 2); insertNode(root, 9); insertNode(root, 1); insertNode(root, 3);
最后,使用树的根节点调用函数postorder(),并以后序方式显示所有树值。如下所示。
cout<<"Post-Order traversal of the Binary Search Tree is: "; postorder(root);
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP