Node class
Class nodetree{
public static Nodetree first;
Public String Value;
Public Nodetree Leftchild;
Public Nodetree Rightchild;
Public Nodetree () {
}
}
public class Tree {
/*
Pre-order (root-left-right): ABCDEF
Middle order (left-root-right): CBDAEF
Post-post (left-right-root): Cdbfea
*/
public static void Main (String []args) {
String a= "ABCDEF";
String b= "CBDAEF";
Buildtree (A,b,null);
New tree (). haha (nodetree.first);
}
Sequential traversal of binary tree
public void haha (nodetree n) {
if (n.leftchild!=null) {
haha (n.leftchild);
}
if (n.rightchild!=null) {
haha (n.rightchild);
}
System.out.print (N.value);
}
Recursive achievements
public static Nodetree Buildtree (String frontchar,string behindchar,nodetree father) {
Nodetree nodetree=new Nodetree ();
if (father==null) {
Create the root node and mark
Nodetree.first=nodetree;
}
Nodetree.value=string.valueof (Frontchar.charat (0));
Determine if there are child nodes
if (Frontchar.length () ==1| | frontchar== "") {
return nodetree;
}
int head=0;
int Mid=behindchar.indexof (Frontchar.charat (head));
Dividing Zuozi
String a=frontchar.substring (1, mid+1);
String b=behindchar.substring (0,mid);
The value of the left node determines if there is Zuozi
if (A.length () >=1&&b.length () >=1)
Nodetree.leftchild=buildtree (A,b,nodetree);
Dividing right sub-tree
String c=frontchar.substring (mid+1, Frontchar.length ());
String d=behindchar.substring (Mid+1,behindchar.length ());
The value of the right node determines if there is a right subtree
if (C.length () >=1&&d.length () >=1)
Nodetree.rightchild=buildtree (C,d,nodetree);
Returns the node of this layer as a child of the upper recursion
return nodetree;
}
}
Simple two-fork tree exercise