Java는 두 갈래 트리의 기본 연산을 실현한다

10210 단어 Java 학습

Java는 두 갈래 트리의 기본 연산을 실현한다

public class BinTree01 {

	static int[] array = {1,2,3,4,5,6,7,8,9};
	static List nodelist = null;
	
	/* */
	public static class Node {
		Node leftChirld;
		Node rightChirld;
		int data;
		public Node(int data) {
			leftChirld=null;
			rightChirld=null;
			this.data=data;
		}
	}
	
	/* */
	public static void build() {
		nodelist=new LinkedList();
		
		for(int node=0;nodenew Node(array[node]));
		}
		
		for(int index=0;index2-1;index++) {
			nodelist.get(index).leftChirld = nodelist.get(index*2+1);
			nodelist.get(index).rightChirld = nodelist.get(index*2+2);
			
		}
		
		int last = array.length/2-1;
		nodelist.get(last).leftChirld = nodelist.get(last*2+1);
		
		/* , */
		if (array.length%2==1) {
			nodelist.get(last).rightChirld = nodelist.get(last*2+2);
		}

	}
	
	/* */
	public static int getHeight(Node node) {
		int treeheight = 0;
		int leftheight = 0;
		int rightheight = 0;
		if (node!=null) {
			leftheight = getHeight(node.leftChirld);
			rightheight = getHeight(node.rightChirld);
			treeheight=leftheight>=rightheight?leftheight+1:rightheight+1;
			
		}
		return treeheight;
	}
	
	/* */
	public static int  getLeafCount(Node node) {
		int num1;
		int num2;
		if (node==null) {
			return 0;
		} else if (node.rightChirld==null && node.leftChirld==null) {
			return 1;
		} else {
			num1=getLeafCount(node.leftChirld);
			num2=getLeafCount(node.rightChirld);
			return num1+num2;
					
		}
			}
	
	/* */
	public static int  getNodeCount(Node node) {
		int num1,num2;
		if (node==null) {
			return 0;
		} else {
			num1=getNodeCount(node.leftChirld);
			num2=getNodeCount(node.rightChirld);
			return num1+num2+1;
			
		}
	}
	
	
	
	
	
	public static void main(String[] args) {
			BinTree01 binTree01 = new BinTree01();
			binTree01.build();
			Node root = nodelist.get(0);
			System.out.println(" :");
			System.out.println(binTree01.getNodeCount(root));
			System.out.println("");
			System.out.println(" ");
			System.out.println(binTree01.getLeafCount(root));
			System.out.println("");
			
			System.out.println(" ");
			System.out.println(binTree01.getHeight(root));
	}

}

좋은 웹페이지 즐겨찾기