一、题目
【问题描述】假设一颗二叉树中每个结点值为单个字符,采用二叉链存储结构存储。设计一个算法,先序遍历方法输出从叶节点到每个叶子结点的路径
【输入形式】A(B(D,E(G,H)),C(,F(I)))
【输出形式】 A->B->D
A->B->E->G
A->B->E->H
A->C->F->I
#include <bits/stdc++.h>
using namespace std;
class Tree
{
public:
typedef struct Node
{
char val, flag;
Node* lchild, * rchild;
};
Node* root;
int numNode;
public:
Tree()
{
root = NULL;
numNode = 0;
}
Node* GetNewNode(char val)
{
Node* ptr = new Node;
assert(ptr != NULL);
ptr->flag = '0';
ptr->val = val;
ptr->rchild = ptr->lchild = NULL;
return ptr;
}
int BuildTree(string str)
{
stack<Node*> sta;
int k = 0; // 璁板綍鏄乏杩樻槸鍙冲瀛?
Node* node = NULL;
for (int i = 0; i < str.size(); i++)
{
char ch = str[i];
switch (ch)
{
case '(':sta.push(node); k = 0; break;
case ')':sta.pop(); break;
case ',':k = 1; break;
default:
{
node = GetNewNode(ch);
if (root == NULL)root = node;
else
{
if (!k)sta.top()->lchild = node;
else sta.top()->rchild = node;
}
break;
}
}
}
return 1;
}
void print()
{
if (root == nullptr) {
return;
}
stack<pair<Node*, string>> stack;
stack.push(make_pair(root, ""));
int k = 0;
while (!stack.empty())
{
pair<Node*, string> p = stack.top();
stack.pop();
Node* curr = p.first;
string path = p.second;
string de = (path == "") ? "\n" : "->";
if (!k)de = "";
path += (de + curr->val);
if (curr->lchild == nullptr && curr->rchild == nullptr) {
cout << path;
if (!stack.empty())cout << endl;
}
if (curr->rchild != NULL) {
stack.push(make_pair(curr->rchild, path));
}
if (curr->lchild != NULL) {
stack.push(make_pair(curr->lchild, path));
}
k++;
}
}
void Test(Node* node)
{
if (node == NULL)return;
cout << node->val << " ";
Test(node->lchild);
Test(node->rchild);
}
};
int main()
{
string str;
cin >> str;
Tree tree;
tree.BuildTree(str);
tree.print();
//tree.Test(tree.root);
return 0;
}
总结
以上就是今天要讲的内容,本文仅仅简单介绍了二叉树广义表的使用,提供了大量能使我们快速便捷地处理数据的函数和方法。
如有疑惑欢迎私信,评论!