给定先序和后续,构造出一颗二叉树并输出中序序列

本文介绍了一种根据前序遍历和中序遍历序列构建二叉树的方法,并提供了详细的算法步骤及C++实现代码。该算法首先从预定义的前序序列中选取元素并递增前序索引,创建一个新节点,接着通过查找中序序列中的对应位置来递归地构建左右子树。

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

Algorithm: buildTree()
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element’s index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.

6) return tNode.


#include <bits/stdc++.h>
 
using namespace std;

struct Node {
	Node(){}
	Node(char data) : data(data) {
	 	left = right = NULL;
	}
 	char data;
 	Node *left, *right;
};

int Search(char *arr, int inst, int inend, char val) {
	for(int i = inst; i <= inend; ++i) {
	 	if(arr[i] == val) {
	 	 	return i;
	 	}
 	}
 	return -1;
}

Node* build(char *in, char *pre, int inst, int inend) {
	static int preIndex = 0;   // just define when first call build, like a overall variable
	Node *tNode = new Node(pre[preIndex++]);
    if(inst > inend) {
     	return NULL;
    }
    if(inst == inend) {
     	return tNode;
    }
    int index = Search(in, inst, inend, tNode->data);
    tNode->left = build(in, pre, inst, index-1);
    tNode->right = build(in, pre, index+1, inend);
    return tNode; 	
}

void inOrder(Node *t) {
 	if(t != NULL) {
 	 	inOrder(t->left);
 	 	cout << t->data << " ";
 	 	inOrder(t->right);
 	}
}

int main(){
    ios::sync_with_stdio(false);
    char in[] = {'D', 'B', 'E', 'A', 'F', 'C'};
    char pre[] = {'A', 'B', 'D', 'E', 'C', 'F'};
    int length = sizeof(in) / sizeof(in[0]);
    Node *root = build(in, pre, 0, length - 1);
    cout << "Inorder traversal of the binary tree is: " << endl;
    inOrder(root);
    return 0;   
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值