二叉树的前序中序后序递归查找,深度,广度搜索C++实现(VS2017)

一、图和运行结果如下

二叉树的前序中序后序递归查找,深度,广度搜索C++实现(VS2017)_第1张图片

二叉树的前序中序后序递归查找,深度,广度搜索C++实现(VS2017)_第2张图片

二、代码如下:

#include
#include
#include
#include
#include
#include
using namespace std;
static int level_count[10];
class BTree
{
public:
	int val;
	BTree *left, *right;
};


class Tree
{
public:
	BTree *root;
	Tree() {
		root = create_node(1, "root");
	}
	BTree *create_node(int level, string pos);
	void PreOrder(BTree *t);
	void InOrder(BTree *t);
	void PostOrder(BTree *t);
	void BFS(BTree *t);
	void DFS(BTree *t);
};

BTree *Tree::create_node(int level, string pos)
{
	int data;
	BTree *node =new BTree;
	cout << "please enter data:level " << level << " " << pos <<" 第"<< ++level_count[level-1]<<"个节点"<< endl;
	cin >> data;

	if (data == 0)
	{
		return NULL;
	}
	node->val = data;

	node->left = create_node(level + 1, "left");
	node->right = create_node(level + 1, "right");
	return node;
}

void Tree::PreOrder(BTree *t)
{
	if (t)
	{
		cout << t->val << " ";
		PreOrder(t->left);
		PreOrder(t->right);
	}
}

void Tree::InOrder(BTree *t)
{
	if (t)
	{
		InOrder(t->left);
		cout << t->val << " ";
		InOrder(t->right);
	}
}

void Tree::PostOrder(BTree *t)
{
	if (t)
	{
		PostOrder(t->left);
		PostOrder(t->right);
		cout << t->val << " ";
	}
}

/*广度优先搜索算法*/
void Tree::BFS(BTree *t)
{
	queue qu;
	qu.push(t);
	BTree *node;
	while (!qu.empty())
	{
		node = qu.front();
		cout << node->val << " ";
		qu.pop();
		if (node->left)
			qu.push(node->left);
		if (node->right)
			qu.push(node->right);
	}
}
/*深度优先搜索算法*/
void Tree::DFS(BTree *t)
{
	stackst;
	st.push(t);
	BTree *node;
	while (!st.empty())
	{
		node = st.top();
		cout << node->val << " ";
		st.pop();
		if (node->right)
		{
			st.push(node->right);
		}
		if (node->left)
		{
			st.push(node->left);
		}
	}
}


int main()
{
	Tree tree;
	cout << "前序:" << endl;
	tree.PreOrder(tree.root);
	cout << "\n中序:" << endl;
	tree.InOrder(tree.root);
	cout << "\n后序:" << endl;
	tree.PostOrder(tree.root);
	cout << "\n广度搜索:" << endl;
	tree.BFS(tree.root);
	cout << "\n深度搜索:" << endl;
	tree.DFS(tree.root);
	return 0;
}

三、运行方式:

每一步会提示输入第几层第几个节点,如果节点不存在,输入为0;

如下图:

二叉树的前序中序后序递归查找,深度,广度搜索C++实现(VS2017)_第3张图片

你可能感兴趣的:(C++)