http://cslibrary.stanford.edu/110/BinaryTrees.html
重点理解:
1.理解递归方法,理解要又一个自变化的递归变量作参数;
2.privateNode insert(Node node,intdata)函数每次调用得到都是root根结点,而不是新加入的新结点.
3.此实现中内部静态类的使用:
1
p.rivate Node root;
private static class Node
二者的顺序,先使用后定义,是由于Node作为静态类先加载。
2,node作为一个简单工厂模式中的产品,将抽象产品,具体产品,工厂角色3者合一之后,并作为内部类,就演变为静态类。
private static class Node {
Node left ;
Node right ;
int data;
Node(int newData) {
left= null;
right= null;
data= newData;
}
static public Node getNode(int newData) {
return new Node(newData);
}
}
// BinaryTree.java
package study;
public class BinaryTree {
// Root node pointer. Will be null for an empty tree.
private Node root;
private static class Node {
Node left ;
Node right ;
int data;
Node(int newData) {
left= null;
right= null;
data= newData;
}
}
/**
Createsanempty binarytree -- a nullrootpointer.
*/
public BinaryTree() {
root= null;
}
/**
Insertsthegiven data into thebinarytree.
Usesarecursive helper.
*/
public void insert(intdata) {
root= insert(root , data);
}
/**
Recursiveinsert-- given a nodepointer,recurdown and
insertthegiven data into thetree.Returnsthenew
nodepointer(thestandardwayto communicate
achangedpointerbackto the caller).
*/
private Node insert(Node node,intdata) {
if(node==null) {
node =new Node(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
}
publicvoid buildTree(int[] data){
for (inti=0;i<data.length;i++){
insert(data[i]);
}
}
publicvoid printTree() {
printTree(root );
System.out .println();
}
privatevoid printTree(Node node) {
if (node ==null)return;
// left, node itself, right
printTree(node.left );
System.out .print(node.data+ " " );
printTree(node.right );
}
}