二叉樹的構造與遍歷

雲苓玉竹發表於2016-03-28

本文用於二叉樹的遍歷與構造:


/*
二叉樹的構造及遍歷

遍歷

1
/   \
2     3
/  \   /  \
4	5	6	7
/  \  /
8	 9 10

先序:
1 根  2 左  3 右  (1,2,3,4,5都是根(父節點))
上述序列:1 2 4 8 9 5 10 3 6 7

中序:
1 左 2 根 3 右
序列:8 4 9 2 10 5 1 6 3 7


後序:
1 左 2 右 3 根
序列:8 9 4 10 5 2 6 7 3 1









*/

//二叉樹鏈式儲存的實現
#include<iostream>
#include<cstring>
#include <vector>
using namespace std;

struct TreeNode
{
	char val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(char x) :val(x), left(nullptr), right(nullptr) {}
};


class Tree
{
private:
	int n;//用於記錄樹節點的總個數
	int n1;//輸入的字元個數
	TreeNode *temp[1000];//用於臨時替換的
public:
	TreeNode *Root;//根
	Tree() //初始化樹
	{
		TreeNode *p;
		char str[1000];
		int parent = 1, child = 0;
		cout << "請輸入字元(例如1#2#3#4#5):";
		cin.getline(str,1000);

		n1 = strlen(str);
		n = 0;

		for (int i = 0; i < n1; i++)
		{
			if (str[i] != '#')
			{
				p = nullptr;
				n++;
				p = new TreeNode(str[i]);
			}
			child++;
			temp[child] = p;
			if (child == 1) { Root = p; }
			else
			{
				if ((p != nullptr) && (child % 2 == 0))
				{
					temp[parent]->left = p;
				}
				if ((p != nullptr) && (child % 2 == 1))
				{
					temp[parent]->right = p;
				}
				if (child % 2 == 1) //in fact, i+1 can replace child 
				{
					parent++;
				}
			}
		}
	}

	~Tree() //釋放記憶體空間
	{
		for (int i = 0; i < n1; i++)
		{
			if (temp[i] != nullptr)
				delete temp[i];
		}
	}

	void Num_n()
	{
		cout << " 該二叉樹的節點個數:" << n << endl;
	}

	void preor(TreeNode * t) //先序遍歷
	{
		if (t != nullptr)
		{
			cout << t->val << ",";
			preor(t->left);
			preor(t->right);
		}
	}

	void midor(TreeNode * t) //中序遍歷
	{
		if (t != nullptr)
		{
			
			midor(t->left);
            cout << t->val << ",";
			midor(t->right);
		}
	}

	void posor(TreeNode * t) //後序遍歷
	{
		if (t != nullptr)
		{

			posor(t->left);
			
			posor(t->right);
            cout << t->val << ",";

		}
	}

};


int main()
{
	Tree tree;
	tree.Num_n();
	cout << "先序遍歷:";
	tree.preor(tree.Root);
	cout << endl;
	cout << "中序遍歷:";
	tree.midor(tree.Root);
	cout << endl;
	cout << "後序遍歷:";
	tree.posor(tree.Root);
	cout << endl;

	system("pause");
	return 0;
}


相關文章