二叉树先序后续。求深度。

/*给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

输入格式 :
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。

输出格式 :
输出为一个整数,即该二叉树的高度。

输入样例 :
9
ABDFGHIEC
FDHGIBEAC
输出样例 :
5*/
/*分析:
先序中的第一个字母把中序分割成两半;中序中的左边为根节点的左子树,右边为根节点的右子树;
不断循环,直到结束。
1.将根节点的值写入;
(根节点的左右儿子信息需要在递归到最后一部分返回)
2.将根节点的左右节点的信息保留在栈中(递归)
3.递归结束条件儿子为空。
/
#include
#define Max 55
using namespace std;
char pre[Max];//先序
char in[Max];//中序
int n;//节点个数
typedef struct Node
Tree;
struct Node {
char item;
Tree Left;
Tree Right;
};
Tree findTree(char pre[],char in[],int lenghth) {
//循环结束条件:lenghth0,即当只剩一个字母时,再向下传递时,传递的数组长度为0;
if (lenghth == 0) return NULL;
//pre[]的第一个元素为根节点。即为pre[0]
Tree head = (Tree)malloc(sizeof(struct Node));
head->item = pre[0];
int i = 0;
for (; i < lenghth; i++ ){
if (in[i] == pre[0]) break;
}
head->Left = findTree(pre + 1, in, i);
head->Right = findTree(pre + i + 1, in + i + 1, lenghth-i-1);
return head;
}
int Length(Tree head) {
if (head
NULL) return 0; //如果为空树返回0;同时如果树的左节点或者又节点为空;返回0
int L = Length(head->Left);
int R = Length(head->Right);
return L > R ? L + 1 : R + 1;
}
int main() {
cin >> n >> pre >> in;
Tree head = findTree(pre, in, n);
int L = Length(head);
cout << L;
return 0;
}

#include<iostream>
#define Max 55
using namespace std;
char pre[Max];//先序
char in[Max];//中序
int n;//节点个数
typedef struct Node* Tree;
struct Node {
    char item;
    Tree Left;
    Tree Right;
};
Tree findTree(char pre[],char in[],int lenghth) {
    //循环结束条件:lenghth==0,即当只剩一个字母时,再向下传递时,传递的数组长度为0;
    if (lenghth == 0) return NULL;
    //pre[]的第一个元素为根节点。即为pre[0]
    Tree head = (Tree)malloc(sizeof(struct Node));
    head->item = pre[0];
    int i = 0;
    for (; i < lenghth; i++) {
        if (in[i] == pre[0]) break;
    }
    head->Left = findTree(pre + 1, in, i);
    head->Right = findTree(pre + i + 1, in + i + 1, lenghth-i-1);
    return head;
}
int Length(Tree head) {
    if (head== NULL) return 0; //如果为空树返回0;同时如果树的左节点或者又节点为空;返回0
    int L = Length(head->Left);
    int R = Length(head->Right);
    return L > R ? L + 1 : R + 1;
}
int main() {
    cin >> n >> pre >> in;
    Tree head = findTree(pre, in, n);
    int L = Length(head);
    cout << L;
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值