Simple two-fork tree exercise

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.