二叉树先序创建_递归_非递归遍历

本文介绍了一种使用先序遍历的方式创建二叉树的方法,并实现了递归与非递归两种先序遍历算法。通过输入字符序列,可以构建出对应的二叉树结构并进行遍历操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


#include "stdafx.h"


/*
 a
/ \
b   c
/\   /
e f  g
*/


// 先序创建顺序:abe##f##cg###


#include <stack>
#include <iostream>
struct bite
{
char data;
struct bite* left;
struct bite* right;
bite()
{
left = NULL;
right = NULL;
}
};


struct bite * create(void)// 创建先序二叉树,最终返回根结点指针
{
struct bite *root;
char a;
std::cin>>a;
if ('#'==a)
{
root = NULL;
}
else
{
root = new bite;
root->data = a;
root->left = create();
root->right = create();
}


return root;
}


void visit(char a)
{
printf("%c\t",a);
}


void preInterverse(struct bite* T,void(*pFun)(char))// 递归遍历先序二叉树
{
if (T)
{
pFun(T->data);
if (T->left)
{
preInterverse(T->left,pFun);
}
if (T->right)
{
preInterverse(T->right,pFun);
}
}
}


void preInterverseNo(struct bite* T,void(*pFun)(char))// 非递归遍历先序二叉树
{
std::stack<struct bite> s;


  struct bite* p = T;
  while (p || !s.empty())
  {
  if (p)
  {
  pFun(p->data);
  s.push(*p);
  p = p->left;
  }
  else
  {
  if (!s.empty())
  {
struct bite& m=s.top();// 返回栈顶元素引用
  s.pop();
  p = m.right;
  }
  }
 
}


int _tmain(int argc, _TCHAR* argv[])
{
struct bite* b = create();
preInterverse(b,visit);
printf("\n");
preInterverseNo(b,visit);
return 0;
}
/*
std::stack<struct bite> s;
struct bite * p=NULL;
*p = s.top();//错误,s.top()只能返回引用
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值