用 C++ 将给定的二叉树转换为双向链表 (Set 2)
本教程中,我们将讨论一个将二叉树转换为双向链表的程序。
为此,我们将提供一棵二叉树。我们的任务是将其转换为一个双向链表,以便左右指针变为上一个和下一个指针。同样,双向链表的顺序排列必须等于二叉树的中序遍历。
为此,我们有不同的方法。我们将倒中序方式遍历二叉树。同时我们将创建新节点并将头指针移动到最新节点;这将从末端到开头创建双向链表。
示例
#include <stdio.h> #include <stdlib.h> //node structure for tree struct Node{ int data; Node *left, *right; }; //converting the binary tree to //doubly linked list void binary_todll(Node* root, Node** head_ref){ if (root == NULL) return; //converting right subtree binary_todll(root->right, head_ref); //inserting the root value to the //doubly linked list root->right = *head_ref; //moving the head pointer if (*head_ref != NULL) (*head_ref)->left = root; *head_ref = root; //converting left subtree binary_todll(root->left, head_ref); } //allocating new node for doubly linked list Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } //printing doubly linked list void print_dll(Node* head){ printf("Doubly Linked list:\n"); while (head) { printf("%d ", head->data); head = head->right; } } int main(){ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->right->right = newNode(8); root->left->left->left = newNode(0); root->left->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(9); Node* head = NULL; binary_todll(root, &head); print_dll(head); return 0; }
输出
Doubly Linked list: 0 1 2 3 4 5 6 7 8 9
广告