L2-006 树的遍历 (c++,python)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

4 1 6 3 5 7 2

分析:

后序遍历:左→右→中    中序遍历:左→中→右

先建树:根据后续遍历的结果可以判断每棵树的根结点,再去中序遍历中找到根结点的位置,在这个位置左边的就是它的左子树的结点,右边的就是它的右子树的结点

再输出:用队列来进行层序遍历(也可以用双指针来模拟队列)

c++(类和对象+队列):

#include"iostream"
#include"queue"
using namespace std;

class tree {
public:
	int data;
	tree* l;
	tree* r;
	tree(int x) :data(x), l(nullptr), r(nullptr) {}
};

tree* build(int a[], int b[], int len) {
	if (!len)return NULL;
	tree* t = new tree(a[len-1]);
	int i = 0;
	for (;i < len;i++)if (b[i] == t->data)break;

	// a[0]到a[i-1]为左子树的结点,a[i]到a[len-2]为右子树的结点
	// b[0]到b[i-1]为左子树的结点,b[i+1]到b[len-1]为右子树的结点
	t->l = build(a, b, i);
	t->r = build(a + i, b + i + 1, len - i - 1);
	return t;
}

// 输出层序遍历的结果
void print(tree *t) {
	// 双指针模拟队列
	/*tree* queue[35];
	if (t) {
		int l = 0, r = 0;
		queue[r++] = t;
		while (l < r) {
			tree* tt = queue[l++];
			if (t != tt)cout << " ";
			cout << tt->data;
			if (tt->l)queue[r++] = tt->l;
			if (tt->r)queue[r++] = tt->r;
		}
	}*/
	// 队列
	if (t) {
		queue<tree*> q;
		q.push(t);
		while (!q.empty()) {
			tree* tt = q.front();
			q.pop();
			if (t != tt)cout << " ";
			cout << tt->data;
			if (tt->l)q.push(tt->l);
			if (tt->r)q.push(tt->r);
		}
	}
}

int main() {
	int n;
	int a[35];
	int b[35];
	cin >> n;
	for (int i = 0;i < n;i++)cin >> a[i];
	for (int i = 0;i < n;i++)cin >> b[i];
	tree* t = build(a, b, n);
	print(t);
}

c++(结构体+数组模拟队列):

#include"iostream"
using namespace std;
typedef struct TNode* Tree;
struct TNode {
    int data;
    struct TNode* l;
    struct TNode* r;
};
Tree queue[100];
Tree build(int a1[], int a2[], int n) {
    if (!n)return NULL;
    Tree t = (Tree)malloc(sizeof(struct TNode));
    t->data = a1[n - 1];
    t->l = t->r = NULL;
    int i = 0;
    for (;i < n;i++) {
        if (a2[i] == a1[n - 1])break;
    }
    t->l = build(a1, a2, i);
    t->r = build(a1+i, a2+i+1, n - i - 1);
    return t;
}
void traverse(Tree t) {
    if (t) {
        int l = 0, r = 0;
        queue[r++] = t;
        while (l < r) {
            Tree tt = queue[l++];
            if (tt != t)cout << " ";
            cout << tt->data;
            if (tt->l)queue[r++] = tt->l;
            if (tt->r)queue[r++] = tt->r;
        }
    }
}
int main() {
    int n;
    int a1[100],a2[100];
    cin >> n;
    for(int i=0;i<n;i++){
        cin >> a1[i];
    }
    for(int i=0;i<n;i++){
        cin >> a2[i];
    }
    Tree T = build(a1, a2, n);
    traverse(T);
}

c++(结构体+队列):

#include"iostream"
#include"queue"
using namespace std;

typedef struct Node* tree;

struct Node {
    int data;
    tree l;
    tree r;
};

tree build(int a1[], int a2[], int n) {
    if (!n)return NULL;
    tree t = new Node;
    t->data = a1[n - 1];
    int i;
    for (i = 0;i < n;i++)if (a2[i] == a1[n - 1])break;
    t->l = build(a1, a2, i);
    t->r = build(a1 + i, a2 + i + 1, n - i - 1);
    return t;
}

queue<tree> q;
void print(tree t) {
    if (t) {
        q.push(t);
        while (q.size()) {
            tree tt = q.front();
            q.pop();
            if (tt != t)cout << " ";
            cout << tt->data;
            if (tt->l)q.push(tt->l);
            if (tt->r)q.push(tt->r);
        }
    }
}

int main() {
    int n;
    int a1[100], a2[100];
    cin >> n;
    for (int i = 0;i < n;i++)cin >> a1[i];
    for (int i = 0;i < n;i++)cin >> a2[i];
    tree t = build(a1, a2, n);
    print(t);
}

python(因为数据量比较小,直接用列表来玩也可以过):

n = int(input())
hx = list(map(int, input().split()))  # 后序遍历序列
zx = list(map(int, input().split()))  # 中序遍历序列


def build(a_start, a_end, b_start, b_end):
    if a_start > a_end:
        return None

    newtree = [hx[a_end], -1, -1]

    # 在中序遍历序列中查找根节点的位置
    root_index = b_start
    while zx[root_index] != newtree[0]:
        root_index += 1

    left_length = root_index - b_start

    newtree[1] = build(a_start, a_start + left_length - 1, b_start, root_index - 1)
    newtree[2] = build(a_start + left_length, a_end - 1, root_index + 1, b_end)

    return newtree


tree = build(0, n - 1, 0, n - 1)

if tree:
    res = []
    queue = [tree]
    while queue:
        now_nodes = []  # 这层的结点的键值
        next_level = []  # 下一层的结点

        for x in queue:
            now_nodes.append(x[0])
            if x[1]:
                next_level.append(x[1])
            if x[2]:
                next_level.append(x[2])

        res.append(now_nodes)
        queue = next_level

cnt = 0
for x in res:
    for y in x:
        if cnt:
            print(" ", end='')
        else:
            cnt = 1
        print(y, end='')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值