---
title: "中序，先序生成树算法"
author: "holoblog"
date: "2007-12-21T11:25:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2011-11-11T11:23:21Z"
id: 1252030
url: "https://holoblog.iteye.com/blog/1252030"
---

输入两个串：

string midOrder = "HDIBJEKALFMCNGO";  
string firstOrder = "ABDHIEJKCFLMGNO";

输出一棵二叉树。

算法思想很简单，在先序中的第一个节点一定是根节点，此节点在中序中的位置可以将中序分为左右两棵子树。如：

根为A,中序分为：HDIBJEK A LFMCNGO,这两棵子树在使用同样的方法就生成一棵树。

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)// 核心算法  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) Node * SetTree( string & midOrder, string & firstOrder)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif) ... {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) if (midOrder.length() == 1 )  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif) ... {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) return new Node(midOrder);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif) }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) string node = firstOrder.substr( 0 , 1 );  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) Node * n = new Node(node);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) size\_ti = midOrder.find(node);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) size\_tj = firstOrder.find(midOrder.substr(i - 1 , 1 ));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) n -&gt; left = SetTree(midOrder.substr( 0 ,i),firstOrder.substr( 1 ,i));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) n -&gt; right = SetTree(midOrder.substr(i + 1 ,midOrder.length() - i - 1 ),firstOrder.substr(j + 1 ,firstOrder.length() - j - 1 ));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) return n;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif) }

中序遍历和后序遍历生成树的算法类似实现。

这里因为每次递归会生成多份string,也创建了大量的额外空间，所以改进此算法，只提供下标即可：

如果思考不清晰，这部分调试起来还是比较困难。需要打印每次递归的信息，最后先使用小数据量，然后打印出来，而不要用gdb调试。源程序是这样打印的：

另外贴上其中的find函数，这里的count其实是找对于start来说的相对位置(师兄说下面这段代码写的很烂，但是烂的凑在一起，竟然没有错，这让我想到了独孤九剑)：

这是为什么呢？因为里面使用到多个判断标准..所以改为：