先序、中序构造一棵唯一的二叉树

来源:互联网 发布:淘宝客成交家信誉吗 编辑:程序博客网 时间:2024/06/06 05:46

直接上代码:

public class BinaryTree{public BinaryTree(String pre,String in){makeTree(pre,in);}public static void main(String[] args){BinaryTree tree=new BinaryTree("ABDCEGFHI","DBAEGCHFI");tree.preOrder();}public void preOrder(){preOrder(this.root);}public void preOrder(BinaryTreeNode n){if(n!=null){visitNode(n);preOrder(n.left);preOrder(n.right);        }}private void visitNode(BinaryTreeNode n){if(n!=null)   System.out.println(n.ele);}private void makeTree(String pre,String in){if(pre!=null){root=new BinaryTreeNode(null,pre.charAt(0),null);if(pre.length()==1)    return;int pareIndex=in.indexOf(pre.charAt(0));if(pareIndex>0&&pareIndex<in.length()-1){        makeTree(certainNode(pre.substring(1,pareIndex+1)),in.substring(0,pareIndex),root,true);        makeTree(certainNode(pre.substring(pareIndex+1)),in.substring(pareIndex+1),root,false);            }            else if(pareIndex==0)            {makeTree(certainNode(pre.substring(1)),in.substring(1),root,false);}else{makeTree(certainNode(pre.substring(1)),in.substring(1,pareIndex-1),root,true);}    }}private void makeTree(String pre,String in,BinaryTreeNode pare,boolean isL){      //~ String s="pre : "+pre+" in : "+in+" right or left :"+((isL)?"left":"right");      //~ System.out.println(s);      BinaryTreeNode parent=null;             if(pre==null)                 return;          if(isL)             parent=pare.left=new BinaryTreeNode(null,pre.charAt(0),null);          else             parent=pare.right=new BinaryTreeNode(null,pre.charAt(0),null);          if(pre.length()==1)             return;           int pareIndex=in.indexOf(pre.charAt(0));           if(pareIndex>0&&pareIndex<in.length()-1)           {   makeTree(certainNode(pre.substring(1,pareIndex+1)),in.substring(0,pareIndex),parent,true);   makeTree(certainNode(pre.substring(pareIndex+1)),in.substring(pareIndex+1),parent,false);   }   else if(pareIndex==0)   {   makeTree(certainNode(pre.substring(1)),in.substring(pareIndex+1),parent,false);   }   else   {   makeTree(certainNode(pre.substring(1)),in.substring(0,pareIndex),pare.left,true);   }}private String certainNode(String s){if(s.length()==0)   return null;else    return s;}private BinaryTreeNode root;private BinaryTreeNode curr; private class BinaryTreeNode{public BinaryTreeNode left;public BinaryTreeNode right;Object ele;BinaryTreeNode(BinaryTreeNode l,Object o,BinaryTreeNode r){left=l;right=r;ele=o;}}}