二叉树
public class BinaryTreeTest {
public static void main(String[] args) {
new BinaryTreeTest().run();
}
static class Node {
Node left;
Node right;
int value;
public Node(int value) {
= value;
}
}
public void run() {
// build the simple tree from chapter 11.
Node root = new Node(5);
("Binary Tree Example");
("Building tree with root value " + );
insert(root, 1);
insert(root, 8);
insert(root, 6);
insert(root, 3);
insert(root, 9);
("Traversing tree in order");
printInOrder(root);
("Traversing tree front-to-back from location 7");
printFrontToBack(root, 7);
}
public void insert(Node node, int value) {
if (value < ) {
if ( != null) {
insert(, value);
} else {
(" Inserted " + value + " to left of "
+ );
= new Node(value);
}
} else if (value > ) {
if ( != null) {
insert(, value);
} else {
(" Inserted " + value + " to right of "
+ );
= new Node(value);
}
}
}
public void printInOrder(Node node) {
if (node != null) {
printInOrder();
(" Traversed " + );
printInOrder();
}
}
/**
* uses in-order traversal when the origin is less than the node's value
*
* uses reverse-order traversal when the origin is greater than the node's
* order
*/
public void printFrontToBack(Node node, int camera) {
if (node == null)
return;
if ( > camera) {
// print in order
printFrontToBack(, camera);
(" Traversed " + );
数据结构笔记 来自淘豆网m.daumloan.com转载请标明出处.