原文鏈接: Depth First Search/Traversal in Binary Tree
目標: -給定一個二叉樹,進行深度優先搜索/遍歷
方法:
- 方法非常簡單,使用棧
- 首先把根節點加入棧
- 從棧中彈出一個元素,然後把它的右孩子和左孩子加入棧
- 彈出一個元素並打印出來,然後把它的孩子加入棧
- 重複上面的兩個步驟直到棧爲空.
例子:
完整代碼:
public class BSTDFS {
public void DFS(Node root) {
Stack<Node> s = new Stack<Node>();
s.add(root);
while (s.isEmpty() == false) {
Node x = s.pop();
if(x.right!=null) s.add(x.right);
if(x.left!=null) s.add(x.left);
System.out.print(" " + x.data);
}
}
public static void main(String args[]){
Node root = new Node(1);
root.left = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right = new Node(3);
root.right.left = new Node(6);
root.right.right = new Node(7);
BSTDFS b = new BSTDFS();
System.out.println("Depth-First-Search : ");
b.DFS(root);
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
left = null;
right = null;
}
}
輸出:
Depth-First-Search :
1 2 4 5 3 6 7