package 樹;
import java.util.ArrayList;
import java.在這裡插入程式碼片util.LinkedList;
import java.util.Queue;
public class 樹的構建 {
public static void main(String[] args) {
TreeNode<Integer> root = new TreeNode<Integer>(1);
MyTree<Integer> tree = new MyTree<Integer>(root);
TreeNode<Integer> childNode2 = new TreeNode<Integer>(2);
tree.insert(root, childNode2);
TreeNode<Integer> childNode3 = new TreeNode<Integer>(3);
tree.insert(root, childNode3);
TreeNode<Integer> childnNode5 = new TreeNode<Integer>(5);
tree.insert(childNode2, childnNode5);
TreeNode<Integer> childNode4 = new TreeNode<Integer>(4);
TreeNode<Integer> childNode6 = new TreeNode<Integer>(6);
tree.insert(childNode3, childNode4);
tree.insert(childNode3,childNode6);
System.out.println(tree.size);
tree.print();
}
}
class TreeNode<Integer>{
int data;
TreeNode<Integer> parent;
ArrayList<TreeNode<Integer>> children;
public TreeNode(int data) {
this.data = data;
}
@Override
public String toString() {
return "TreeNode [data=" + data + "]";
}
}
class MyTree<Integer>{
int size = 0;
TreeNode<Integer> root;
public MyTree(TreeNode<Integer> root){
this.root = root;
size++;
}
public void insert(TreeNode<Integer> p,TreeNode<Integer> child){
if(p.children==null){
p.children = new ArrayList<TreeNode<Integer>>();
}
p.children.add(child);
child.parent = p;
size++;
}
public void print(){
Queue<TreeNode<Integer>> queue = new LinkedList<TreeNode<Integer>>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode<Integer> dxl = queue.poll();
System.out.println(dxl);
if(dxl.children!=null)
for(TreeNode<Integer> ttt:dxl.children)
queue.add(ttt);
}
}
}