满二叉树通过先序得出后序

#include<iostream>
using namespace std;
char res[7];
int n=6;
char a[7]={'A','B','D','E','C','F','G'};

void bulid(int l1,int h1,int l2,int h2){  
//为什么这么写? 前面的l1 和h1是分别代表着 从什么位置拿走字母 也就是我们一开始所需要的确定l1(通过先序的规律   后面的为了确定h2 也就是确定放在那(通过后序的规律 
	if(h1 >=l1  ){
		res[h2] = a[l1];
		int mid = (h1-l1)/2;
		bulid(l1+1,l1+mid,l2,l2+mid-1);
		bulid(l1+mid+1,h1,l2+mid,h2-1);
	}
}

int main(){
	bulid(0,6,0,6);
	for(int i=0;i<7;i++){
		cout << res[i] <<" ";
	}
	return 0;
	
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是用C语言实现按先序遍历创建二叉树的代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; TreeNode *createTree() { int val; scanf("%d", &val); if (val == -1) { // -1表示该节点为NULL return NULL; } TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); root->val = val; root->left = createTree(); root->right = createTree(); return root; } void preorder(TreeNode *root) { if (root == NULL) { return; } printf("%d ", root->val); preorder(root->left); preorder(root->right); } void inorder(TreeNode *root) { if (root == NULL) { return; } inorder(root->left); printf("%d ", root->val); inorder(root->right); } void postorder(TreeNode *root) { if (root == NULL) { return; } postorder(root->left); postorder(root->right); printf("%d ", root->val); } void levelorder(TreeNode *root) { if (root == NULL) { return; } TreeNode *queue[1000]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { TreeNode *cur = queue[front++]; printf("%d ", cur->val); if (cur->left) { queue[rear++] = cur->left; } if (cur->right) { queue[rear++] = cur->right; } } } int main() { printf("请输入二叉树的先序遍历结果,-1表示该节点为NULL:\n"); TreeNode *root = createTree(); printf("先序遍历结果为:"); preorder(root); printf("\n中序遍历结果为:"); inorder(root); printf("\n后序遍历结果为:"); postorder(root); printf("\n层次遍历结果为:"); levelorder(root); printf("\n"); return 0; } ``` 输入示例: ``` 请输入二叉树的先序遍历结果,-1表示该节点为NULL: 1 2 -1 -1 3 4 -1 -1 5 -1 -1 ``` 输出示例: ``` 先序遍历结果为:1 2 3 4 5 中序遍历结果为:2 1 4 3 5 后序遍历结果为:2 4 5 3 1 层次遍历结果为:1 2 3 4 5 ``` 希望这个程序能够帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值