package algorithm;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class DFS {
static class TreeNode{
int value;
TreeNode left;
TreeNode right;
TreeNode(int value){
this.value=value;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr=new int[]{1,2,3,4,5,6,7};
TreeNode root=getBinaryTree(arr,0);
System.out.println("\n深度优先搜索:");
getDFS(root); //深度优先搜索 。。使用栈实现深度优先
System.out.println("\n广度优先搜索:");
getBFS(root); //广度优先搜索 。。使用队列实现广度优先搜索
}
//队列为先进先出
//Java中还定义了一种双端队列java.util.Deque,我们常用的LinkedList就是实现了Deque接口。
/*
1
2 3
4 5 6 7
队列为先进先出:
首先构建队列:队列添加root节点,移出root节点,元素为1,添加左节点(2),右节点(3),队列非空,移出2,添加4,5
此时为:3,4,5,
接着:移出3,添加6,7,此时为:
4 ,5 ,6 ,7 ,循环为广度优先搜索
1 ——》2->3
*/
private static void getBFS(TreeNode root) {//广度优先搜索
if(root==null){
return;
}
//Deque实现双端队列,LinkedList就实现了Deque接口
Queue<TreeNode> myQueue=new LinkedList<TreeNode>();
myQueue.add(root);
while(!myQueue.isEmpty()){
TreeNode node=myQueue.poll(); //移出顶端元素
System.out.print(node.value+"\t");
if(node.left!=null){
myQueue.add(node.left);
}
if(node.right!=null){
myQueue.add(node.right);
}
}
}
/*
1
2 3
4 5 6 7
栈为先进后出:
首先构建栈:队列添加root节点,移出root节点,元素为1,添加右节点(3),之后左节点(2),此时为:
2
3
之后,开始2,添加右5,左4,此时为:
4
5
3
接着4,5均为子节点,搜索出,接着为3
3,添加右7,左6
6
7
此时为:3,4,5,
接着:移出3,添加6,7,此时为:
4 ,5 ,6 ,7 ,循环为广度优先搜索
1 ——》2->4->5->3-6->7
*/
private static void getDFS(TreeNode root) { //深度优先搜索
if(root == null){
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
//TreeNode temp = stack.peek();
TreeNode temp = stack.pop();
System.out.print(temp.value+"\t");
//stack.pop();
if(temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
//System.out.println(root+""+stack);
}
private static TreeNode getBinaryTree(int[] arr, int index) {
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;
}
}
528

被折叠的 条评论
为什么被折叠?



