新手问一个关于根据先序,中序构建二叉树问题!!
java实现程序代码:
public class Binarytree { BTNode root; int i; String s; public Binarytree(){ String[] Pre="A B C I D E H F J G".split(" "); String[] Mid="B I C A H E J F G D".split(" "); root=BuildFromPreMid(Pre,Mid,0,Pre.length-1,0,Mid.length-1); lastorder(root); } public void preorder(BTNode tn){ if(tn!=null){ System.out.print(tn.S+" "); preorder(tn.left); preorder(tn.right); } } public void midorder(BTNode tn){ if(tn!=null){ midorder(tn.left); System.out.print(tn.S+" "); midorder(tn.right); } } public void lastorder(BTNode tn){ if(tn!=null){ lastorder(tn.left); lastorder(tn.right); System.out.print(tn.S+" "); } } BTNode BuildFromPreMid(String[] Pre,String[] Mid,int PS,int PE,int MS,int ME){ BTNode node=new BTNode(); node.S=Pre[PS]; int i=0; while(!Mid[MS+i].equals(node.S)){ i++; } if(i>0){ node.left=BuildFromPreMid(Pre,Mid,PS+1,PS+i,MS,MS+i-1); } if(MS+i<ME){ node.right=BuildFromPreMid(Pre,Mid,PS+i+1,PE,MS+i+1,ME); } return node; } public static void main(String[] args) { Binarytree b=new Binarytree(); } class BTNode{ String S; BTNode right,left,parent; } }
这个是别人的代码,可以实现
我想问的是在构建左右子数时候
if(i>0){
node.left=BuildFromPreMid(Pre,Mid,PS+1,PS+i,MS,MS+i-1);
}
if(MS+i<ME){
node.right=BuildFromPreMid(Pre,Mid,PS+i+1,PE,MS+i+1,ME);
}
这一段我没看懂,有大神讲解下吗谢谢!!!ps:ps为先序开始,pe为先序结束,ms为中序开始,me为中序结束
[此贴子已经被作者于2016-11-24 14:25编辑过]