例题:假设一颗二叉树中每个结点值为单个字符,采用二叉链存储结构存储。设计一个算法,先序遍历方法输出从根节点到每个叶子结点的路径

一、题目

【问题描述】假设一颗二叉树中每个结点值为单个字符,采用二叉链存储结构存储。设计一个算法,先序遍历方法输出从叶节点到每个叶子结点的路径

【输入形式】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;
}


总结

以上就是今天要讲的内容,本文仅仅简单介绍了二叉树广义表的使用,提供了大量能使我们快速便捷地处理数据的函数和方法。

如有疑惑欢迎私信,评论!

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值