首页 > 代码库 > 简单的二叉树练习
简单的二叉树练习
//节点类
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=http://www.mamicode.com/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;
}
}
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=http://www.mamicode.com/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;
}
}
简单的二叉树练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。