poj-2255 已知数的前序与中序遍历序列,求后序遍历序列
2013-03-27 20:07
330 查看
算法来自于http://www.java3z.com/cwbwebhome/article/article18/report076.html?id=4765
--------------------------------
首先,树的任意子树的遍历结点序列一定是该树的遍历结点序列的一个连续子序列。preorder的第一个结点是根, 设为root,root这个结点会把inorder分为2部分(可能某部分为空), 左边的就是左子树的中序遍历结点序列,右边的就是右子树的中序遍历结点序列,
这样也就确定了左子树和右子树的结点数目,根据左右子树结点数目, 就可得到左右子树的先序遍历结点序列,从而问题就递归了。
已知左右子树的先序遍历结点序列和中序遍历结点序列,求后序遍历结点序列,递归求解即可。递归边界是叶子结点。
--------------------------------
首先,树的任意子树的遍历结点序列一定是该树的遍历结点序列的一个连续子序列。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(); } }
相关文章推荐
- POJ 2255 二叉树遍历 已知前序遍历 中序遍历 求后序遍历
- POJ 2255 Tree Recovery(根据前中序遍历,求后序遍历)
- 已知中序遍历序列和后序遍历序列,求先序遍历
- POJ - 2255 (由前序遍历,中序遍历,求后序)
- poj 2255 二叉树的后序遍历
- POJ 2255 根据二叉树的前序和中序序列来重建二叉树
- POJ 2255 Tree Revovery 二叉树遍历序列推导
- 二叉树系列(二):已知中序遍历序列和后序遍历序列,求先序遍历序列
- POj2255 利用先序,中序输出后序序列
- 已知后序遍历是dabec,中序遍历是debac,它的前序遍历的序列是什么?
- 已知后序遍历是dabec,中序遍历是debac,它的前序遍历的序列是什么?
- poj2255 由前序遍历和中序遍历导出后序遍历
- 二叉树遍历,先序序列+中序序列=后序序列,Poj(2255)
- poj2255 二叉树给出先序中序求后序序列
- POJ 2255(已知前中序遍历 还原树)
- poj2750 Potted Flower(区间连续子序列的和)
- poj 1836 Alignment( 最长上升(下降)子序列 )
- poj 5187(单调序列问题+快速乘)
- Poj 1077 eight(BFS+全序列Hash解八数码问题)
- 《剑指Offer》读书笔记---面试题24:二叉搜索树的后序遍历序列