码迷,mamicode.com
首页 > 其他好文 > 详细

简单的二叉树练习

时间:2016-10-29 22:19:55      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:div   first   string   sys   substring   cdb   dtree   null   tree   

//节点类
class NodeTree{
    public static NodeTree first;
    public String Value;
    public NodeTree leftChild;
    public NodeTree rightChild;
    public NodeTree(){
        
    }    
}
public class tree {
    
    /*
        前序(根-左-右):ABCDEF
        中序(左-根-右):CBDAEF
        后序(左-右-根):CDBFEA
     */
    public static void main(String []args){
        String a="ABCDEF";
        String b="CBDAEF";
        buildTree(a,b,null);    
        new tree().haha(NodeTree.first);
    }
    
    //后序遍历二叉树
    public void haha(NodeTree n){
        if(n.leftChild!=null){
            haha(n.leftChild);         
        }
        if(n.rightChild!=null){
            haha(n.rightChild);             
        }
        System.out.print(n.Value);
    }
    
    //递归建树
    public static NodeTree buildTree(String frontChar,String behindChar,NodeTree father){
        
        NodeTree nodeTree=new NodeTree();
        if(father==null){    
            //创立根节点并标记
            NodeTree.first=nodeTree;                
        }  
        
        nodeTree.Value=String.valueOf(frontChar.charAt(0));
        
        //判断是否有子节点
        if(frontChar.length()==1||frontChar==""){
            return nodeTree ;
        }        
        
        int head=0;
        int mid=behindChar.indexOf(frontChar.charAt(head));    
        
        //划分左子树
        String a=frontChar.substring(1, mid+1);
        String b=behindChar.substring(0,mid);        
        //左节点的值 判断是否有左子树
        if(a.length()>=1&&b.length()>=1)
        nodeTree.leftChild=buildTree(a,b,nodeTree);    
        
        //划分右子树
        String c=frontChar.substring(mid+1, frontChar.length());
        String d=behindChar.substring(mid+1,behindChar.length());        
        //右节点的值 判断是否有右子树
        if(c.length()>=1&&d.length()>=1)
        nodeTree.rightChild=buildTree(c,d,nodeTree);
        
        //返回本层节点 作为上层递归的子节点
        return nodeTree;
    }    
}

简单的二叉树练习

标签:div   first   string   sys   substring   cdb   dtree   null   tree   

原文地址:http://www.cnblogs.com/Seeing/p/6011771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!