java實現樹

weixin_43771734發表於2020-10-29
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);
		}
	}
	
}

相關文章