您的位置:首页 > 其它

poj-2255 已知数的前序与中序遍历序列,求后序遍历序列

2013-03-27 20:07 330 查看
算法来自于http://www.java3z.com/cwbwebhome/article/article18/report076.html?id=4765

--------------------------------

首先,树的任意子树的遍历结点序列一定是该树的遍历结点序列的一个连续子序列。preorder的第一个结点是根, 设为root,root这个结点会把inorder分为2部分(可能某部分为空), 左边的就是左子树的中序遍历结点序列,右边的就是右子树的中序遍历结点序列,
这样也就确定了左子树和右子树的结点数目,根据左右子树结点数目, 就可得到左右子树的先序遍历结点序列,从而问题就递归了。

已知左右子树的先序遍历结点序列和中序遍历结点序列,求后序遍历结点序列,递归求解即可。递归边界是叶子结点。

package onlineJudge;

import java.util.Scanner;

class Node{
Node left;
Node right;
char value;

Node()
{
left = null;
right = null;
}
}

public class Poj2255_FindPostOrderOfTree {

/**
* @param args
*/
static Node BuildBinaryTree(char pre[], int pre_start, char in[], int in_start,  int len)
{
if(pre.length == 0 || in.length == 0 | len == 0)
return null;

Node root = new Node();
root.value = pre[pre_start];

if(len == 1)
return root;

int i;
for(i = 0; i < len; i++)
{
if(in[in_start + i] == pre[pre_start])
break;
}

root.left = BuildBinaryTree(pre, pre_start + 1, in, in_start, i);
root.right = BuildBinaryTree(pre, pre_start+i+1, in, in_start+i+1, len-i-1);
return root;
}

static void postOrderPrint(Node root)
{
if(root != null)
{
postOrderPrint(root.left);
postOrderPrint(root.right);
System.out.print(root.value);
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner scan = new Scanner(System.in);
while(scan.hasNext())
{
String pre = scan.next();
String in = scan.next();
Node root = BuildBinaryTree(pre.toCharArray(), 0, in.toCharArray(), 0, pre.length());
postOrderPrint(root);
System.out.print("\n");
}

scan.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: