树是一种很常用的数据结构,日后的学习中会经常碰到运用树的知识。

//构造二叉树
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
/*
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
*/
typedef struct node{
int data;
node *l;
node *r;
}*tree;
tree head,t; //head为头指针,同时为根节点,t为当前的节点
void dis(tree &p) //删除二叉树
{
if(p)
{
dis(p->l);
dis(p->r);
delete p;
}
}
void build(tree &p) //先读入根节点,再从左到右
{
int n;
cin>>n;
if(n != -)
{
p = new node;
p -> data = n;
build(p -> l);
build(p -> r);
}
else
p = NULL;
}
void frontvisit(tree p)
{
if(p)
{
cout<< p->data <<" ";
frontvisit(p->l);
frontvisit(p->r);
}
}
void midvisit(tree p)
{
if(p)
{
midvisit(p->l);
cout<<p->data<<" ";
midvisit(p->r);
}
}
void backvisit(tree p)
{
if(p)
{
backvisit(p->l);
backvisit(p->r);
cout<<p->data<<" ";
}
}
void in(tree &p,int n)
{
if(p)
{
if(n < p->data)
in(p->l,n);
if(n > p->data)
in(p->r,n);
}
else
{
p = new node;
p->data = n;
p->l = p->r =NULL;
}
}
int main()
{
int x;
build(t);
cin>>x;
in(t,x);
cout<<"frontvisit"<<endl;
frontvisit(t);
cout<<endl;
cout<<"midvisit"<<endl;
midvisit(t);
cout<<endl;
cout<<"backvisit"<<endl;
backvisit(t);
cout<<endl;
return ;
}
/*
5 3 2 1 -1 -1 -1 -1 6 -1 7 -1 -1
4
*/

最新文章

  1. js学习进阶-页面覆盖
  2. STL数组处理常用函数
  3. jsp include page指令标记
  4. bzoj2178: 圆的面积并
  5. Linux网络编程——连接和面向连接的协议之间没有区别
  6. Java基于TCP的Socket编程练习
  7. 如何优雅的利用Windows服务来部署ASP.NET Core程序
  8. Python_多进程
  9. Analysis Services(SSAS) 性能优化
  10. 6 week work 2
  11. Ubuntu 16.04安装Notepadqq编辑器替代Notepad++
  12. 【托业】【新东方托业全真模拟】TEST05~06-----P5~6
  13. vs2017 使用Bower 抛出异常ECMDERR Failed to execute &quot;git ls-remote --tags --heads
  14. boost asio 学习(一)io_service的基础
  15. 实验验证sys和system用户全库导出的区别
  16. SQLGetConnectAttr
  17. Codeforces 769D k-Интересные пары чисел
  18. [LeetCode] 628. Maximum Product of Three Numbers_Easy
  19. node(6)angular介绍
  20. Cocoa Touch(四): 多线程GCD, NSObject, NSThread, NSOperationQueue

热门文章

  1. Struts2框架实现简单的用户登入
  2. (转)OGNL与值栈
  3. lldb e、@weakify(self) 网络请求400错误
  4. django 加日志
  5. Git学习总结四(删除)
  6. C#基础速学
  7. JS对象中,在原型链上找到属性后 最终将值拷贝给原对象 而不是引用
  8. 生成元(Digit Generator, ACM/ICPC Seoul 2005, UVa1583)
  9. linu学习第二天:文件系统相关操作
  10. Shell脚本备份文件