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