Java二叉樹的創建及遍歷

	//定義二叉樹節點
	public static class Node {
		Node left;	//左節點
		Node right;		//右節點
		Integer value;	//節點值
		
		public void add(Integer v)	//插入節點
		{
			if(value == null)
				value = v;
			else
			{
				if(v-this.value<=0)
				{
					if(this.left==null)
						this.left = new Node();
					left.add(v);
				}
				else
				{
					if(this.right==null)
						this.right = new Node();
					right.add(v);
				}
			}
		}
	}
	
	//二叉樹先序遍歷
	public static void preOrderTraverse(Node root)
	{
		if(root == null) return;
		else
		{
			System.out.print(root.value + " ");
			preOrderTraverse(root.left);
			preOrderTraverse(root.right);
		}
	}
	
	//二叉樹中序遍歷
	public static void inOrderTraverse(Node root)
	{
		if(root == null) return;
		else
		{
			inOrderTraverse(root.left);
			System.out.print(root.value + " ");
			inOrderTraverse(root.right);
		}
	}
	
	//二叉樹後序遍歷
	public static void postOrderTraverse(Node root)
	{
		if(root == null) return;
		else
		{
			postOrderTraverse(root.left);
			postOrderTraverse(root.right);
			System.out.print(root.value + " ");
		}
	}
	
	//二叉樹層序遍歷
	public static void levelOrderTraverse(Node root)
	{
		LinkedList<Node> arr = new LinkedList<>();
		arr.offer(root);
		while(!arr.isEmpty())
		{
			int size = arr.size();
			for(int i = 0; i < size; i++)
			{
				Node tmp = arr.poll();
				System.out.print(tmp.value + " ");
				if(tmp.left!=null) arr.offer(tmp.left);
				if(tmp.right!=null) arr.offer(tmp.right);
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[] = new int[] { 67, 7, 30, 73, 10, 8, 78, 81, 11, 74 };
		Node root = new Node();
		//創建二叉樹
		for(int x: arr)
		{
			root.add(x);
		}
		preOrderTraverse(root);
		System.out.println();
		inOrderTraverse(root);
		System.out.println();
		postOrderTraverse(root);
		System.out.println();
		levelOrderTraverse(root);
	}
發佈了38 篇原創文章 · 獲贊 87 · 訪問量 7312
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章