链式存储一个完全二叉树代码:
//二叉树(链式存储) import java.util.ArrayDeque; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; public class MyTree { static Node root; class Node{ private Node lChild; private Node rChild; private int data; Node(int d){ data=d; } public Node getlChild() { return lChild; } public void setlChild(Node lChild) { this.lChild = lChild; } public Node getrChild() { return rChild; } public void setrChild(Node rChild) { this.rChild = rChild; } public int getData() { return data; } public void setData(int data) { this.data = data; } } //创建二叉树 Node creatTree(int[] a){ List<Node> nodelist = new LinkedList<>(); for(int i=0;i<a.length;i++){ nodelist.add(new Node(a[i])); } for(int i=0;i<a.length/2-1;i++){ nodelist.get(i).setlChild(nodelist.get(2*i+1)); nodelist.get(i).setrChild(nodelist.get(2*i+2)); } int index = a.length/2-1; nodelist.get(index).setlChild(nodelist.get(2*index+1)); if(a.length%2==1){ nodelist.get(index).setrChild(nodelist.get(2*index+2)); } root=nodelist.get(0); return root; } //先序遍历 void preOrder(Node n){ if(n==null){ return; } System.out.print(n.getData()+" "); preOrder(n.getlChild()); preOrder(n.getrChild()); } //求高度 int getHeight(Node n){ if(n==null){ return 0; }else { int left = getHeight(n.getlChild()); int right = getHeight(n.getrChild()); return 1+Math.max(left, right);// 每向上返回一层,加一 } } //深度优先遍历(dfs) void dfsOrder(){ if(root==null){ System.out.println("empty tree"); return; } Stack<Node>stack=new Stack<>(); stack.push(root); while(!stack.isEmpty()){ Node node = stack.pop(); System.out.print(node.getData()+" "); if(node.getrChild()!=null){ stack.push(node.getrChild()); } if(node.getlChild()!=null){ stack.push(node.getlChild()); } } } //广度优先遍历(bfs) void bfsOrder(){ if(root==null){ System.out.println("empty tree"); } Queue<Node>queue=new ArrayDeque<>(); queue.add(root); while(!queue.isEmpty()){ Node n = queue.remove(); System.out.print(n.getData()+" "); if(n.getlChild()!=null){ queue.add(n.getlChild()); } if(n.getrChild()!=null){ queue.add(n.getrChild()); } } } //求树的宽度 int getWeight(Node n){ if(n==null){ return 1; } Queue<Node>queue = new ArrayDeque<>(); queue.add(n); int maxsize=1;//最大长度 while(true){ int len = queue.size();//当前层节点数 if(len==0){ break; //跳出 }while(len>0){ //如果还有当前层节点 Node node = queue.poll(); len--; if(node.getlChild()!=null){ queue.add(node.getlChild()); }if(node.getrChild()!=null){ queue.add(node.getrChild()); } } maxsize = Math.max(maxsize, queue.size());//新入队之前最大的宽度与新入队的大小取较大值 } return maxsize; } }
测试:
public static void main(String[] args) { int[] arr = {1,2,3,4,78,6,7,8,9}; MyTree m = new MyTree(); Node node = m.creatTree(arr); m.preOrder(node); System.out.println(); System.out.println("该树高度为"+m.getHeight(root)); System.out.println("深度优先遍历:"); m.dfsOrder(); System.out.println(); System.out.println("广度优先遍历:"); m.bfsOrder(); System.out.println(); System.out.println("该树的宽度为:"+m.getWeight(root)); }
测试结果: