如果用Google搜索技术类问题,没有比较好的文章,那么用英文,所以这里输入 binary trees就得到了斯坦福大学用c/c++ , Java三种语言解答的这个问题:http://cslibrary.stanford.edu/110/BinaryTrees.html
// BinaryTree.java
packageTree;
publicclassBinaryTree {
// Root node pointer. Will be null for an empty tree.
privateNoderoot;
privatestaticclassNode {
Nodeleft;
Noderight;
intdata;
Node(intnewData) {
left=null;
right=null;
data= newData;
}
}
/**
Createsanemptybinarytree--anullrootpointer.
*/
publicBinaryTree() {
root=null;
}
/**
Insertsthegivendataintothebinarytree.
Usesarecursivehelper.
*/
publicvoidinsert(intdata) {
root= insert(root, data);
}
/**
Recursiveinsert--givenanodepointer,recurdownand
insertthegivendataintothetree.Returnsthenew
nodepointer(thestandardwaytocommunicate
achangedpointerbacktothecaller).
*/
privateNode insert(Node node,intdata) {
if(node==null) {
node =newNode(data);
}
else{
if(data <= node.data) {
node.left= insert(node.left, data);
}
else{
node.right= insert(node.right, data);
}
}
return(node);// in any case, return the new pointer to the caller
}
publicvoidbuildTree(int[] data){
for(inti=0;i<data.length;i++){
insert(data[i]);
}
}
publicvoidprintTree() {
printTree(root);
System.out.println();
}
privatevoidprintTree(Node node) {
if(node ==null)return;
// left, node itself, right
printTree(node.left);
System.out.print(node.data+"");
printTree(node.right);
}
}
测试类代码如下:
//test.java
public class test {
public static void main(String[] args) {
BinaryTree biTree=new BinaryTree();
int[] data={2,8,7,4};
biTree.buildTree(data);
biTree.printTree();
}
}