-
简介
前序数组遍历方法: 根–>左子树–>右子树
中序数组遍历方法: 左子树–>根–>右子树
以 前序数组"ABDGCEFH";中序数组"DGBAECHF" 为例, -
演示
第一次 前序数组可知 根为A 再根据中序数组可知左子树为DGB 右子树为ECHF
|根| 左子树 |右子树
| A| DGB |ECHF
第二次(左子树 DGB) 根据前序数组 BDG可知 根为B 再根据中序数组DGB可知左子树为DG 右子树为空
|根| 左子树 |右子树
|B|DG |null
第三次 左子树 DG 根据前序数组 DG可知 根为D 再根据中序数组DG可知左子树为空 右子树为G
|根| 左子树 |右子树
|D|null |G
同理可以推出右子树结构
//定义节点
```static class node{
node rchild;
node lchild;
String data;
node(String ndata)
{
data=ndata;
rchild=null;
lchild=null;
}
public node() {
rchild=null;
lchild=null;
}
}
//l—left r-- right pre前序 in 中序
//substring(int start,int end) 取 start-->(end-1)
//substring(int start) 取 start-->结束
public static node sort(String pre,String in) throws Exception
{
if(pre.length()!= in.length()) //异常处理
throw new Exception("前序和中序长度不同");
if(pre.length()>0)
{
String t_root=pre.substring(0,1);
node node=new node(t_root);
int l_len=in.indexOf(t_root);//左子树的长度
String l_pre=pre.substring(1,1+l_len);//左子树前序
String r_pre=pre.substring(1+l_len);//左子树中序
String l_in=in.substring(0, l_len);;//右子树前序
String r_in=in.substring(l_len+1);//左子树中序
node.lchild=sort(l_pre,l_in); //递归调用 生成左子树
node.rchild=sort(r_pre,r_in); //递归调用 生成右子树
return node;
}
else {
return new node(pre);
}
}
//前序遍历
public static void pre(node root)
{
if(root!=null) {
System.out.print(root.data.toString());
pre(root.lchild);
pre(root.rchild);
}
}
//中序遍历
public static void in(node root)
{
if(root!=null) {
in(root.lchild);
System.out.print(root.data.toString());
in(root.rchild);
}
}
下面为测试代码
String pre="ABDGCEFH";
String in="DGBAECHF";
node temp=sort(pre,in);
System.out.print("前序");
pre(temp);
System.out.println();
System.out.print("中序");
in(temp);