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

前序遍历结果为:6 4 1 5 8
执行前序递归遍历的程序如下所示。
示例
#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 preorder(struct node *root) {
if (root != NULL) {
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
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<<"Pre-Order traversal of the Binary Search Tree is: ";
preorder(root);
return 0;
}输出
Pre-Order traversal of the Binary Search Tree is: 4 2 1 3 5 9
在上面的程序中,结构体node创建树的节点。这个结构体是一个自引用结构体,因为它包含struct node类型的指针。该结构体如下所示。
struct node {
int data;
struct node *left;
struct node *right;
};createNode()函数创建一个节点temp并使用malloc为其分配内存。数据值val存储在temp的data中。NULL存储在temp的左、右指针中。这由以下代码片段演示。
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}preorder()函数以二叉树的根节点作为参数,并按前序打印树的元素。这是一个递归函数。它使用以下代码演示。
void preorder(struct node *root) {
if (root != NULL) {
cout<<root-->data<<" ";
preorder(root-->left);
preorder(root-->right);
}
}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);
最后,使用树的根节点调用preorder()函数,并以前序显示所有树值。如下所示。
cout<<"Pre-Order traversal of the Binary Search Tree is: "; preorder(root);
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP