用java实现一个二叉树,节点有一个值,为value,int类型。设法将这些节点组织成一棵树,并实现这些节点得遍历。
package structure.composite;
import java.util.*;
public class Node {
private Node leftChild;
private Node rightChild;
private int value;
public static Vector v=new Vector();
public int getValue() {
return value;
}
public Node(int value){this.value=value;}
public void setValue(int value) {
this.value = value;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
public Node getLeftChild() {
return leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void getAllChildren(){
if(leftChild!=null){
v.add(leftChild);
leftChild.getAllChildren();
}
if(rightChild!=null){
v.add(rightChild);
rightChild.getAllChildren();
}
}
public int getAllChildrenValue(){
int sum=0;
if(leftChild!=null){
sum+=leftChild.getValue();
sum+=leftChild.getAllChildrenValue();
}
if(rightChild!=null){
sum+=rightChild.getValue();
sum+=rightChild.getAllChildrenValue();
}
return sum;
}
}
package structure.composite;
import java.util.*;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
Node node5=new Node(5);
node1.setLeftChild(node2);
node2.setRightChild(node3);
node3.setLeftChild(node4);
node2.setLeftChild(node5);
System.out.println(node1.getAllChildrenValue());
node1.getAllChildren();
Vector v=Node.v;
Iterator i=v.iterator();
while(i.hasNext()){
System.out.println(((Node)i.next()).getValue()+":");
}
}
}