编程解二叉树先序、中序、后序遍历相互求法

我们经常会遇到这种问题:已知二叉树先序、中序、后序遍历中的两种,求另外一种排序。一般做这种题都是画出二叉树然后写出另一种遍历,今天系统地研究了一下,发现其实我们也可以用编程的方法来完成。
若已知先序、中序遍历,求后序遍历以及已知中序、后序遍历,求先序遍历是可以实现的,而已知先序、后序遍历,求中序遍历无法完成,因为这种情况下若一个结点只有一条边,此时不知道这条边到底是左子树还是右子树。

已知先序、中序遍历,求后序遍历

可以用递归来实现,步骤为:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
我们用这种方式来输出这棵树:
使用的树
代码为:

#include <iostream>  
#include <fstream>  
#include <string>  
using namespace std;
struct TreeNode{
   struct TreeNode* left;
   struct TreeNode* right;
   char  data;
};
 
void BinaryTreeFromOrderings(char* inorder, char* preorder, int length){
	int rootIndex=0;
  	if(length==0){
       return;
     }
   TreeNode* node = new TreeNode;
   node->data=*preorder;
   for(;rootIndex<length;rootIndex++){
    	if(inorder[rootIndex]==*preorder){
    		break;
		}
    }
   //Left
   BinaryTreeFromOrderings(inorder, preorder+1,rootIndex);
   //Right
   BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
   cout<<node->data<<endl;
   return;
}
 
int main(){
    char* pr="GDAFEMHZ";
    char* in="ADEFGHMZ";
    BinaryTreeFromOrderings(in,pr,8);
    printf("\n");
    return 0;
}

输出结果:
后序遍历
经检验,该结果为正确的。

已知中序、后序遍历,求先序遍历

求解过程依然使用递归且思路与上面类似:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
依然使用输出上面那颗树。
代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct TreeNode{
    struct TreeNode* left;
    struct TreeNode* right;
    char data;
};

TreeNode* BinaryTreeFromOrderings(char* inorder,char* aftorder,int length){
    if(length == 0){
        return NULL;
    }
    TreeNode* node= new TreeNode;
    node->data=*(aftorder+length-1);
    cout<<node->data<<endl;
    int rootIndex=0;
    for(;rootIndex<length;rootIndex++){
        if(inorder[rootIndex]==*(aftorder+length-1))
            break;
    }
    node->left=BinaryTreeFromOrderings(inorder,aftorder,rootIndex);
    node->right=BinaryTreeFromOrderings(inorder+rootIndex+1,aftorder+rootIndex,length-(rootIndex+1));
    return node;
}

int main(){
    char* af="AEFDHZMG";    
    char* in="ADEFGHMZ"; 
    BinaryTreeFromOrderings(in,af,8); 
    printf("\n");
    return 0;
}

输出结果为:
先序遍历
经检验,该结果也是正确的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值