[英]Java reconstruction tree from postorder and preorder
Hy, i have some troubles i want to reconstructe tree with two travelsar (postorder and preoorder). 嗨,我有些麻烦,我想用两个travelsar(后置和前置)重建树。 I saw on netbeans at least 5 hours and i cant solve problem with my this code.
我在netbeans上看到至少5个小时,但是我的这段代码无法解决问题。 If anyone saw what i make wrong or give me other reconstruction.
如果有人看到我做错了或给我其他重建。 I will be vary grateful
我将不胜感激
import java.util.Arrays;
import java.util.List;
public class ReConstructBTree {
/**
* @param args
*/
public static void main(String[] args) {
String[] pre = "I Q J H L E M V O T S B R G Y Z K C A & F P N U D W X".split("\\s");
String[] post = "H E M L J V Q S G Y R Z B T C P U D N F W & X A K O I".split("\\s");
List preList = Arrays.asList(pre);
List postList = Arrays.asList(post);
BTree tree = reBuildTree(preList, postList);
tree.inOrder(tree); //print in-order
System.out.println();
tree.postOrder(tree);//print post order to re-check
System.out.println();
tree.preOrder(tree);//print pre order to re-check
}
private static BTree reBuildTree(List preList, List postList) {
BTree tree = null;
if(preList.size() != 0 && postList.size() != 0) {
tree = new BTree();
String val = preList.get(0);
tree.val = val;
if(preList.size() > 1 && postList.size() > 1) {
int postOrderPos = postList.indexOf(preList.get(1));
int preOrderPos = preList.indexOf(postList.get(postList.size()-2));
//find the two sub set of the list from pre-order
List leftPreOrder = preList.subList(1, preOrderPos);
List rightPreOrder = preList.subList(preOrderPos, preList.size());
//find the two sub set of the list from post-order
List leftPostOrder = postList.subList(0, postOrderPos+1);
List rightPostOrder = postList.subList(postOrderPos+1, postList.size()-1);
tree.left = reBuildTree(leftPreOrder, leftPostOrder);
tree.right = reBuildTree(rightPreOrder, rightPostOrder);
}
}
return tree;
}
static class BTree {
String val;
BTree left;
BTree right;
void inOrder(BTree tree) {
if(tree.left != null)
inOrder(tree.left);
System.out.print(tree.val+" ");
if(tree.right != null)
inOrder(tree.right);
}
void preOrder(BTree tree) {
System.out.print(tree.val+" ");
if(tree.left != null)
preOrder(tree.left);
if(tree.right != null)
preOrder(tree.right);
}
void postOrder(BTree tree) {
if(tree.left != null)
postOrder(tree.left);
if(tree.right != null)
postOrder(tree.right);
System.out.print(tree.val+" ");
}
}
}
This code can only reconstruction 2 depth or low.. 此代码只能重建2个深度或更低的深度。
What type of tree are you constructing ?? 您要建造哪种树? General Binary Tree reconstruction uniquely is
not possible from just pre-order and post-order traversal.
仅通过顺序遍历和顺序遍历就不可能唯一地进行通用二叉树重构。 ( Refer here for explanation and more discussion )
(请参阅此处进行解释和更多讨论 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.