C++ 数据结构 二叉树操作


基本知识点不讲了,直接说遍历问题:

前序遍历:根节点->左子树->右子树

中序遍历:左子树->根节点->右子树

后序遍历:左子树->右子树->根节点

具体看代码【未完待续,困,明天继续】

//  BinaryTreeTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <stack>
using namespace std;
// 定义二叉树接点数据类型
typedef char datatype;

// 定义二叉树结点
typedef struct BinNode
{
	datatype data;
	struct BinNode *lchild;
	struct BinNode *rchild;

}*pBinNode, *BinTree;

// 递归实现
void CreateBinTree(BinTree &T)
{
	datatype c;
	cin >> c;
	if ('#'== c)
	{
		T = NULL;
	}
	else
	{
		T = new BinNode;
		T->data = c;
		CreateBinTree(T->lchild);
		CreateBinTree(T->rchild);
	}

}

// 前序遍历
void PreOrder(BinTree t)
{
	if (t != NULL)
	{
		cout << t->data;
		PreOrder(t->lchild);
		PreOrder(t->rchild);
	}
}
// 中序遍历
void InOrder(BinTree t)
{
	if (t != NULL)
	{
		InOrder(t->lchild);
		cout << t->data;
		InOrder(t->rchild);
	}
}
// 后序遍历
void PosOrder(BinTree t)
{
	if (t != NULL)
	{
		PosOrder(t->lchild);
		PosOrder(t->rchild);
		cout << t->data;
	}
}
// 非递归实现,需要结合堆栈实现
// 前序遍历
/* 对于任一结点P:
1)访问结点P,并将结点P入栈;
2)判断结点P的左孩子是否为空,
	若不为空,输出当前结点值,当前结点指针入栈,左孩子置为当前的结点P;
	若为空,取栈顶结点,栈顶结点的右孩子为当前的结点P;	
3)直到P为NULL并且栈为空,则遍历结束。
*/
void PreOrderNonRecursive(BinTree t)
{
	if (NULL == t)
	{
		return;
	}

	stack<pBinNode> stackNodes;
	pBinNode node = t;
	while (node != NULL || !stackNodes.empty())
	{
		while (node != NULL)
		{
			cout << node->data;
			stackNodes.push(node);
			node = node->lchild;
		}

		if (!stackNodes.empty())
		{
			node = stackNodes.top();
			stackNodes.pop();
			node = node->rchild;
		}
	}
}
// 中序遍历
/*  对于任一结点P:
1)当前非空结点入栈,结点左孩子赋值为当前结点,直到结点为空
2)取栈顶元素并进行出栈操作,访问该栈顶结点值,结点右孩子赋值为当前结点;
3)直到P为NULL并且栈为空则遍历结束
*/
void InOrderNonRecursive(BinTree t)
{
	if (NULL == t)
	{
		return;
	}

	stack<pBinNode> stackNodes;
	pBinNode node = t;
	while (node != NULL || !stackNodes.empty())
	{
		while (node != NULL)
		{
			stackNodes.push(node);
			node = node->lchild;
		}
		if (!stackNodes.empty())
		{
			node = stackNodes.top();
			stackNodes.pop();
			cout << node->data;
			node = node->rchild;
		}
	}
}

// 后序遍历
/*
*/
void PosOrderNonRecursive(BinTree t)
{
	if (NULL == t)
	{
		return;
	}
	stack<pBinNode> stackNodes;
	pBinNode node = t;
	while (node != NULL || !stackNodes.empty())
	{

	}

}
int _tmain(int argc, _TCHAR* argv[])
{
	BinTree tree;
	// 递归实现
	CreateBinTree(tree);
	cout << "递归遍历: \n";

	cout << "前序:\n";
	PreOrder(tree);
	cout << "\n中序:\n";
	InOrder(tree);
	cout << "\n后序:\n";
	PosOrder(tree);

	cout << "\n\n非递归遍历: \n";
	cout << "\n前序:\n";
	PreOrderNonRecursive(tree);
	cout << "\n中序:\n";
	InOrderNonRecursive(tree);
	cout << "\n后序:\n";

	return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值