廣度優先遍歷簡介和實現
廣度優先遍歷(Breadth First Search)簡介:
廣度優先遍歷,指的是從圖的一個未遍歷的節點出發,先遍歷這個節點的相鄰節點,再依次遍歷每個相鄰節點的相鄰節點。
實現:
package search;
import java.util.Stack;
/**
* @author huchenfei
* @version 1.0
* @className DepthFirstSearch
* @description 二叉樹深度遍歷算法
* 先從根節點沿着(左或者右)分支走到底,當再也沒有葉子節點之後,返回上一節點
* 如果上一個節點還有另外一個子節點,那麼遍歷這個節點分支直至再也沒有葉子節點,之後重複上面的過程
* @date 2020/6/2 15:38
**/
public class DepthFirstSearch {
private static class Node {
/**
* 節點值
*/
public int value;
/**
* 左節點
*/
public Node left;
/**
* 右節點
*/
public Node right;
public Node(int value) {
this.value = value;
}
}
public static void main(String... args) {
Node head = new Node(1);
Node second = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
Node seven = new Node(7);
head.right = three;
head.left = second;
second.right = five;
second.left = four;
three.right = seven;
three.left = six;
System.out.println("遞歸方式 -> 深度優先遍歷結果: ");
recursiveDfs(head);
System.out.println();
System.out.println("非遞歸方式 -> 深度優先遍歷結果: ");
unRecursiveDfs(head);
System.out.println();
}
/**
* 遞歸方式實現 DFS
*
* @param head 二叉樹
*/
public static void recursiveDfs(Node head) {
if (head == null) {
return;
}
System.out.print(head.value);
System.out.print(" ");
// 遍歷左節點
recursiveDfs(head.left);
// 遍歷右節點
recursiveDfs(head.right);
}
/**
* 非遞歸的使用棧來實現 DFS
* 依據棧的先進後出特性
* 1. 將二叉樹的頭結點放入棧中
* 2. 將頭結點 1 從棧中彈出,並查看頭結點是否有左右節點,將右節點和左節點壓入棧中【3,2】
* 3. 將頭結點 2 從棧中彈出,並查看 2 節點是否有左右節點,將右節點和左節點壓入棧中【3,5,4】
* 4. 將頭結點 4 從棧中彈出,無左右節點【3,5】
* 5. 將頭結點 5 從棧中彈出,無左右節點【3】
* 6. 將頭結點 3 從棧中彈出,並查看 3 節點是否有左右節點,將右節點和左節點壓入棧中【7,6】
* 7. 將頭結點 6 從棧中彈出,無左右節點【7】
* 8. 將頭結點 7 從棧中彈出,無左右節點
*
* @param head 二叉樹
*/
public static void unRecursiveDfs(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<>();
// 先將根結點壓入棧中
stack.push(head);
while (!stack.isEmpty()) {
Node node = stack.pop();
System.out.print(node.value);
System.out.print(" ");
// 將節點右邊的壓入棧中
if (node.right != null) {
stack.push(node.right);
}
// 壓入左邊的棧中
if (node.left != null) {
stack.push(node.left);
}
}
}
}
拓展
參考: