Recently studied the binary tree structure, reference to some data, summed up a bit.
package com.test;
/** *//**
*
* Implements the two-fork tree structure in Java
*
* Explanation:
* Two method functions, one looking for the keyword--searchkey the other is inserting a node: Inserttree
*
* In addition this is a complete first-order traversal of the binary tree syntax. First root node, then left node, such as no more right node, such as some add to
*
* Search completed.
*
*/
public class Binarytreetest ... {
private BinaryTree root = null;
public binarytreetest () ... {
init ();
}
/** *//**
* Initializes the two-fork tree structure of the given data
*
*/
private void init () ... {
int data[] = ... {12, 11, 34, 45, 67, 38, 56, 43, 22, 8};
root = new BinaryTree (data[0]);
System.out.println ("Data structure in binary tree:");
System.out.println ("------------------------------------");
System.out.println (Data[0] + ": root");
for (int i = 1; i < data.length; i++) ... {
System.out.print (Data[i] + ":");
Root.inserttree (Root, data[i]);
}
System.out.println ("------------------------------------");
}
public void Serach (int key) ... {
if (Searchkey (root, key)) ... {
System.out.println ("Found:" + key);
} else ... {
System.out.println ("Not found:" + key);
}
}
Private Boolean Searchkey (BinaryTree root, int key) ... {
if (root = null) ... {
return false;
} else if (Root.data = = key) ... {
return true;
} else if (key >= root.data) ... {
return Searchkey (Root.rightpoiter, key);
}
Return Searchkey (Root.leftpoiter, key);
}
class BinaryTree ... {
int data;
BinaryTree Leftpoiter;
BinaryTree Rightpoiter;
BinaryTree (int data) ... {
this.data = data;
leftpoiter = null;
rightpoiter = null;
}
private void Inserttree (BinaryTree root, int data) ... {
if (data >= root.data) ... {
if (root.rightpoiter = null) ... {
System.out.println ("-> new Rightpoiter");
root.rightpoiter = new BinaryTree (data);
} else ... {
System.out.print ("-> rightpoiter");
Inserttree (root.rightpoiter, data);
}
} else ... {
if (root.leftpoiter = null) ... {
System.out.println ("-> new Leftpoiter");
root.leftpoiter = new BinaryTree (data);
} else ... {
System.out.print ("-> leftpoiter");
Inserttree (root.leftpoiter, data);
}
}
}
}
public static void Main (String args[]) ... {
binarytreetest B = new Binarytreetest ();
int key = 8; Key: Any numeric
B.serach (key); Find
in a two-fork tree
}
}