来自后序和预订的Java重建树

时间:2014-04-09 13:49:27

标签: java

HY, 我有一些麻烦,我想用两个旅行车(后序和前期)重建树。我在netbeans上看到至少5个小时,我无法用我的代码解决问题。如果有人看到我做错了或给我其他重建。我会感激不尽

    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+" ");
  }

 }
}

此代码只能重建2个深度或更低..

1 个答案:

答案 0 :(得分:0)

你在建造什么类型的树?一般二进制树重建唯一不可能来自预订和后订单遍历。 (请参阅此处查看explanationmore discussion