java实现简单的二叉树

package com.xtm.tree;

import java.util.LinkedList;

public class Main {

	/**
	 * 树:
	 *           1
	 *       2       3
	 *     4   5   6   7
	 *   8   9
	 * 
	 */
	public static void main(String[] args) {
		//建立树
		int[] array = {1,2,3,4,5,6,7,8,9};
		int len = array.length;
		LinkedList<TreeNode> linkedList = new LinkedList<TreeNode>();
		for(int i=0;i<len;i++){
			linkedList.add(new TreeNode(array[i]));
		}
		
		for(int i=0;i<len/2-1;i++){
			linkedList.get(i).left=linkedList.get(i*2+1);
			linkedList.get(i).right=linkedList.get(i*2+2);
		}
		
		int lastIndex = len/2-1;
		linkedList.get(lastIndex).left=linkedList
				.get(lastIndex*2+1);
		if(len%2==1){
			linkedList.get(lastIndex).right=linkedList
					.get(lastIndex*2+2);
		}
				
		//遍历树
		printTreeNode(linkedList.get(0));

	}



	private static void printTreeNode(TreeNode root) {
		if(root == null){
			return ;
		}
		//System.out.print(root.value+"\t");//先序遍历:先父后左子右子    输出:1 	2	4	8	9	5	3	6	7
		printTreeNode(root.left);
		//System.out.print(root.value+"\t");//中序遍历:先左子后父再右子 输出:8	4	9	2	5	1	6	3	7
		printTreeNode(root.right);
		System.out.print(root.value+"\t");//后序遍历,先左右子后父              输出:8	9	4	5	2	6	7	3	1
		
	}

}

class TreeNode{
	TreeNode left ;
	TreeNode right ;
	int value ;
	public TreeNode() {
	}
	public TreeNode(int value) {
		this.value = value;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_17441227/article/details/79241959
今日推荐