1. 程式人生 > >Java二叉樹構建及深度優先遍歷和廣度優先遍歷

Java二叉樹構建及深度優先遍歷和廣度優先遍歷

1.工程目錄如下:

2.定義節點資訊的類:TreeNode.java

package binarytree;

public class TreeNode{
	public TreeNode() {
		// TODO Auto-generated constructor stub
	}
	int value;
	TreeNode left;
	TreeNode right;
	public TreeNode(int value) {
		// TODO Auto-generated constructor stub
		this.value = value;
	}
}

3.構建樹的類:BinaryTree.java

package binarytree;

public class BinaryTree {
//	private TreeNode root = new TreeNode();
	public TreeNode getBinaryTree(int[] arr, int index) {
		// TODO Auto-generated method stub
		TreeNode node = null;
		if(index < arr.length){
			int value = arr[index];
			node = new TreeNode(value);
			node.left = getBinaryTree(arr, index*2+1);
			node.right = getBinaryTree(arr, index*2+2);
			return node;
		}
		return node;
	}
}

4.深度優先遍歷的類:DFS.java

package binarytree;

import java.util.Stack;


public class DFS {
	public void getDFS(TreeNode root){
		if(root == null){
			return;
		}
		Stack<TreeNode> stack = new Stack<>();

		stack.push(root);
		while(!stack.isEmpty()){
			TreeNode temp = stack.peek();
			System.out.print(temp.value+"\t");
			stack.pop();
			if(temp.right != null){
				stack.push(temp.right);
			}
			if(temp.left != null){
				stack.push(temp.left);
			}
		}
	}
}

5.廣度優先遍歷的類:BFS.java

package binarytree;

import java.util.ArrayList;


public class BFS {
	public void getBFS(TreeNode root) {
		// TODO Auto-generated method stub
		if(root == null){
			return;
		}
		ArrayList<TreeNode> queue = new ArrayList<>();
		queue.add(root);
		while(queue.size() > 0){
			TreeNode temp = queue.get(0);
			queue.remove(0);
			System.out.print(temp.value+"\t");
			if(temp.left != null){
				queue.add(temp.left);
			}
			if(temp.right != null){
				queue.add(temp.right);
			}
		}
	}
}

6.測試類:Test.java

package binarytree;


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = new int[]{
				1,2,3,4,5,6,7
		};
		BinaryTree binaryTree = new BinaryTree();
		TreeNode root = binaryTree.getBinaryTree(arr, 0);
		new DFS().getDFS(root);
		System.out.println("\n深度優先遍歷結束。。。");
		new BFS().getBFS(root);
		System.out.print("\n廣度優先遍歷結束。。。");
	}

}

其中測試的二叉樹如下:

7.測試結果如下: