[重修数据结构0x01]二叉树的存储和遍历(2021.8.6)

前言

毕 业快半年,数据结构也快忘的差不多了,仔细想想大学这四年真正学到的知识寥寥无几,可唯一值得软件工程9800*8学费的是这四年里自己做出的种种努力,尽管它们中的大多数都以失败告终。大学能为学生提供的资源很多,但很少会有人主动把它们送到你嘴边,资源是需要自己主动去争取的。在校园的环境中,这种对资源的争取就像一场以小博大的豪赌。即使失败了也没什么大不了,成本几乎可以忽略不计,但一旦成功,能够得到无法用成本衡量的收获。如果多年之后自己回想起来,我可以问心无愧地告诉自己,当时的失败是自己能力不足,而不是我不敢我好怕
说的有些偏题了,一想起来这些心里也是百感交集,说起来也不怕笑话,数据结构和微机原理这两个是我当年考的最差的专业课,当初还念念不忘的成绩,现在看起来也不是那么难以接受,但又不愿坦然接受自己就是失败者这一事实,毕竟先尽人事然后才能听天命,之前没尽的力也许现在还能有所弥补,所以趁着没开学补一下数据结构的知识,聊以打发时间,躺平之余掺杂我这最后的一丝倔强
(代码都是手打的,错误请指正感谢,,0x00标题留着)
在这里插入图片描述

正文

一. 二叉树的定义与存储、查找修改、插入、建树.

1.1二叉树的递归定义

struct node{
	int data;  // 数据域int类型
	node* lchild;
	node* rchild;
};
node* root = NULL;

1.2 二叉树新建节点

node* newNode(int v)
{
	node* Node = new node;
	Node->data = v;
	Node->lchild = Node->rchild = NULL;
	return Node;
}

1.3 二叉树结点的查找和操作

void search(node* root, int x, int newdata)
{
	if(root == NULL)
		return ;
	if(root->data == x)
		root->data == newdata;
	search(root->lchild,x,newdata);
	search(root->rchild,x,newdata);
}

1.4二叉树结点的插入

void insert(node* &root,int x)
{
	if(root == NULL)
		root = newNode(x);
		return;
	if(二叉树性质,插在左子树)
		insert(root->lchild,x)else
		insert(root->rchild,x)}

二 . 二叉树的前序(先根)、中序、后序遍历。二叉树的层次遍历(两种方法)。

2.1先序遍历

void preorder(node* root)
{
	if(root == NULL)
		return ;
	cout<<root->data; //对结点进行操作
	preorder(root->lchild);
	preorder(root->rchild);
}

2.2层次遍历

void levelorder(node* root)
{
	queue<node*> q;
	q.push(root);
	while(!q.empty())
	{
		node* now =  q.front();
		q.pop();
		cout<<now->data;            //对结点进行访问和操作
		if(now->lchild!=NULL) q.push(now->lchild);
		if(now->rchild!=NULL) q.push(now->rchild);
	}
}

2.3 由先序和中序建树

递归边界是先序区间小于0

//先序区间为pre[preL,preR]
//中序区间为in[inL,inR]

node* Create(int preL,int preR,int inL,int inR)
{
	if(preL>preR)	return NULL; //递归出口,很重要
	node* root = new node;
	root->data = pre[preL];
	int k ;
	for(k = inL; k <= inR;k++)
		{
			if(in[k] == pre[preL])
				break;
		}
	int numLeft = k - inL;
	
	root->lchild = Create(preL+1 , preL+numLeft, inL, k-1); // 两边都是闭区间
	// 闭区间要注意-1,例如【2,4】实际上是三个数字,(2,4】就是两个数字
	//这个经常用到,虽然简单,但初学者应该记住这个规律
	root->rchild = Create(preL+numleft+1, preR, k+1, inR);
	
	return root;
}

2.4 二叉树的数组实现和转换

有时候不方便建树,需要

三.简单入门题目和知识补充

忘记的知识:string的find()substr()函数,输入方式getline(cin,varibles);
C中的strcmp(a,b)函数,string是C++的方法,strcmp无法直接比较string类

以前经常用,现在想用却不熟练,复习一下。

**substr有2种用法:
假设:string s = "0123456789";
string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = "56789"

string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = "567"**

**find() 查找第一次出现的目标字符串:
如果查找成功则输出查找到的第一个位置,否则返回-1
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
    string s1 = "abcdef";
    string s2 = "de";
    int ans = s1.find(s2) ;   //在S1中查找子串S2
    cout<<ans<<endl;
    system("pause");
}
** strcmp(a,b)
返回值:-x,0,x (x>0)
如果返回值 < 0,则表示 str1 小于 str2。
如果返回值 > 0,则表示 str2 小于 str1。
如果返回值 = 0,则表示 str1 等于 str2。

** "varible name " does name a type 错误。一般是作用域写错了.
** 字符转数字:char-'0'即可
**复制粘贴之后一定要检查代码,很有可能产生错误!
**如何dubug段错误

关于段错误的描述

3.1 UVA536 二叉树重建 Tree Recovery

链接:https://www.luogu.com.cn/problem/UVA536
题意:输入一棵二叉树的先序遍历和中序遍历序列,输出它的后序遍历序列

输入:
DBACEGF ABCDEFG
BCAD CBAD
输出:
ACBFGED
CDAB
#include <iostream>
#include <cstring>

using namespace std;

string preorder,inorder;

void postorder(string pre,string in)
{
    if(pre.size()<=0)
        return ;
    int len = 0;
    len = in.find(pre[0]);
    postorder(pre.substr(1,len),in.substr(0,len));
    postorder(pre.substr(len+1),in.substr(len+1));
    cout<<pre[0];
}
int main()
{
    while(cin>>preorder>>inorder)
    {
        postorder(preorder,inorder);
        cout<<endl;
    }
    return 0;
}

3.2 P1335 新二叉树

题意:
输入一串二叉树,输出其前序遍历

输入:
第一行为二叉树的节点数 n(1<=n<=26)
后面 n 行,每一个字母为节点,后两个字母分别为其左右儿子。
空节点用 * 表示
6
abc
bdi
cj*
d**
i**
j**
输出:
abdicj
#include <iostream>

using namespace std;

struct node
{
    char data;
    node* lchild;
    node* rchild;
};
node* root = NULL;

node* newNode(char a)
{
    node* Node = new node;
    Node->data = a;
    Node->lchild = NULL;
    Node->rchild = NULL;
    return Node;
}
void preorder(node* root)
{
    if(root == NULL)
        return ;
    if(root->data!='*') cout<<root->data;
    preorder(root->lchild);
    preorder(root->rchild);
}

void search1(node* root,char a,char b)
{
    if(root == NULL)
        return ;
    if(root->data == a)
        root->lchild = newNode(b);
    search1(root->lchild,a,b);
    search1(root->rchild,a,b);
}
void search2(node* root,char a,char b)
{
    if(root==NULL)
        return ;
    if(root->data == a)
        root->rchild = newNode(b);
    search2(root->lchild,a,b);
    search2(root->rchild,a,b);
}
int main()
{
    int n;
    cin>>n;
    string s ;
    cin>>s;
    root = newNode(s[0]);
    root ->lchild = newNode(s[1]);
    root ->rchild = newNode(s[2]);
    for(int i=2;i<=n;i++)
    {
        cin>>s;
        search1(root,s[0],s[1]);
        search2(root,s[0],s[2]);

    }
    preorder(root);
    return 0;
}

3.3 UVA548 树 Tree

题意:
输入一个二叉树的中序和后序遍历,请你输出一个叶子节点,该叶子节点到根的数值总和最小,且这个叶子是编号最小的那个。 输入: 您的程序将从输入文件中读取两行(直到文件结尾)。第一行是树的中序遍历值序列,第二行是树的后序遍历值序列。所有值将不同,大于零且小于或等于10000.二叉树的节1<=N<=10000。 输出: 对于每个树描述,您应该输出最小值路径的叶节点的值。存在多路径最小的情况下,您应该选择终端叶子节点上具有最小值的那条路径,且输出那个最小值的终端叶子。

输入:
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255

输出:
1
3
255

3.4 PTA A1020 Tree Traversals

题目链接:A1020 Tree Traversals

题意:给后序和中序遍历,求层次遍历,第一行n,表示n个结点。
输入:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出:
4 1 6 3 5 7 2

自己写的解:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int t =0 ;
int n;
int pos[50],in[50];
struct node
{
    int data;
    node* lchild;
    node* rchild;
};

node* Create(int posL,int posR,int inL,int inR)
{
    if(posL>posR)   return NULL;
    node* root = new node;
    root->data = pos[posR];
    int k;
    for(k=inL;k<=inR;k++)
       {
           if(in[k]==pos[posR])
            break;
       }
    int numleft = k-inL;
    root->lchild = Create(posL,posL+numleft-1,inL,k-1);
    root->rchild = Create(posL+numleft,posR-1,k+1,inR);
    return root;
}
void levelorder(node* root)
{
    queue<node*> q;
    q.push(root);
    while(!q.empty())
    {
        node* now = q.front();
        q.pop();
        cout<<now->data;
        t++;
        if(t<n) cout<<' ';
        if(now->lchild!=NULL)   q.push(now->lchild);
        if(now->rchild!=NULL)   q.push(now->rchild);
    }
}
int main()
{
      cin>>n;
      for(int i=0;i<n;i++)
        cin>>pos[i];
      for(int i=0;i<n;i++)
        cin>>in[i];

      node* root = Create(0,n-1,0,n-1);
      levelorder(root);

    return 0;
}

3.5 PTA A1086 Tree Traversals Again

题目地址:1086 Tree Traversals Again (25 分)

题意:用栈来模拟一棵二叉树的先序和中序遍历过程,求这棵二叉树的后序遍历序列。
输入:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

输出:
3 4 2 6 5 1
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;

int n;
int pre[50],in[50];
int pt = 0;
int it = 0;
int out = 0;
struct node{
    int data;
    node* lchild;
    node* rchild;
};
node* create(int preL,int preR,int inL,int inR)
{
    if(preL>preR) return NULL;
    node* now = new node;
    now->data = pre[preL];
    int k;
    for(k = inL;k <= inR;k++)
    {
        if(in[k]==pre[preL])
            break;
    }
    int numleft = k -inL ;

    now->lchild = create(preL+1,preL+numleft,inL,k-1);

    now->rchild = create(preL+numleft+1,preR,k+1,inR);

    return now;

}

void posorder(node* root)
{
    if(root == NULL) return ;
    posorder(root->lchild);
    posorder(root->rchild);
    cout<<root->data;
    if(out<n-1)
        cout<<' ';
    out++;
}
int main()
{
    cin>>n;
    stack<int> st;
    for(int i=0;i<2*n;i++)
    {
        char s[10];
        cin>>s;
        if(strcmp(s,"Push")==0)
        {
            int t;
            cin>>t;
            pre[pt++] = t ;
            st.push(t);
        }
        if(strcmp(s,"Pop")==0)
        {
            int tep = st.top();
            st.pop();
            in[it++] = tep;
        }
    }

    node* root = create(0,n-1,0,n-1);

    posorder(root);
    return 0;
}

弄清题意很重要。

3.6 PTA A1102 Invert a Binary Tree

题目地址:1102 Invert a Binary Tree (25 分)

题意:二叉树有N个结点,编号(0-N-1),给出每个结点的左右孩子结点的编号,把该二叉树反转(即把每个结点的左右子树都交换),输出反转后的二叉树的层次遍历序列和中序遍历序列。1-N行代表0到N-1结点的左右子树结点号。

想法:先建树,后序遍历,最后访问根节点的时候交换左右子树。
关键是建树函数和交换函数。

输入:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

题外话:由于目前基层程序开发岗位供大于求,因此在短时间考察一个求职者有几大要素,1学历能最快的区分开一大批人,残酷但事实。2.算法题,能够帮助面试官迅速挑选出应届生中写过题的人,即使这些人开发没什么经验。3.八股文。开发经验多的对于面经理解更深,而不是基础知识的简单堆砌。说多了,偏题太远。。。
这天后,leetcode悄悄添加了一道叫invert binary tree 的题目
我的解:

#include <iostream>
#include <stack>
#include <queue>
#include <cstring>
using namespace std;

bool ver[100];
int cnt1,cnt2;
int n;
struct staNode
{
    int lchild;
    int rchild;
}InNode[100];

struct node
{
    int data;
    node* lchild;
    node* rchild;
}Node[100];

node* create(int root)
{
    if(root == -1) return NULL;
    node* now = new node;
    now->data = root;
    now->lchild = create(InNode[root].lchild);
    now->rchild = create(InNode[root].rchild);

    return  now;
}
void inorder(node* root)
{
    if(root == NULL) return ;

    inorder(root->lchild);
    cout<<root->data;
    if(cnt1<n-1) cout<<' ';
        cnt1++;
    inorder(root->rchild);
}

void levelorder(node* root)
{
    queue<node*> q;
    q.push(root);
    while(!q.empty())
    {
        node* now = q.front();
        q.pop();
        cout<<now->data;
        if(cnt2<n-1) cout<<' ';
        cnt2++;
        if(now->lchild!=NULL) q.push(now->lchild);
        if(now->rchild!=NULL) q.push(now->rchild);
    }
}

int FindRoot(int n)
{
    for(int i=0;i<n;i++)
    {
        if(InNode[i].lchild!=-1)
            ver[InNode[i].lchild] = true;
        if(InNode[i].rchild!=-1)
            ver[InNode[i].rchild] = true;

    }
    for(int i=0;i<n;i++)
    {
        if(ver[i]==false)
            return i;
    }
    return -1;

}

void swa(node* root)
{
    node* tmp = root->lchild;
    root->lchild = root->rchild;
    root->rchild = tmp;
}
void invert(node* root)
{
    if(root == NULL) return;
        invert(root->lchild);
        invert(root->rchild);
        swa(root);
}
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
    {
        char ch1,ch2;
        cin>>ch1>>ch2;
        if(ch1=='-')
            InNode[i].lchild = -1;
        if(ch1!='-')
            InNode[i].lchild = ch1-'0';
        if(ch2=='-')
            InNode[i].rchild = -1;
        if(ch2!='-')
            InNode[i].rchild = ch2-'0';
    }
    int root = FindRoot(n);
    node* ans = create(root);
    invert(ans);
    levelorder(ans);
    cout<<endl;
    inorder(ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值