當前位置:編程學習大全網 - 編程軟體 - 設二叉樹以二叉鏈表存儲,試設計算法,實現二叉樹的層序遍歷。

設二叉樹以二叉鏈表存儲,試設計算法,實現二叉樹的層序遍歷。

按層次遍歷算法如下:

#include <iostream>

using namespace std;

typedef struct treenode { //樹結點結構

int data;

struct treenode *left;

struct treenode *right;

}TreeNode;

typedef struct stack{ //棧結點結構

TreeNode *node;

struct stack *next;

}STACK;

void Traversal(TreeNode *root)

{

STACK *head = NULL;

STACK *tail = NULL;

if (root != NULL) //根結點入棧

{

head = new STACK();

head->next = NULL;

head->node = root;

tail = head;

}

while(head != NULL)

{

STACK *temp;

if (head->node->left != NULL) //棧頂結點的左結點入棧

{

temp = new STACK();

temp->next = NULL;

temp->node = head->node->left;

tail->next = temp;

tail = temp;

}

if (head->node->right != NULL) //棧頂結點的右結點入棧

{

temp = new STACK();

temp->next = NULL;

temp->node = head->node->right;

tail->next = temp;

tail = temp;

}

cout<<head->node->data<<endl; //結點出棧

temp = head;

head = head->next;

delete(head);

}

}

  • 上一篇:快影視頻開頭黑屏加字幕怎麽做的
  • 下一篇:什麽是嵌入式 Qt?
  • copyright 2024編程學習大全網