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