對於二叉樹
代碼結構:
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
一個節點包含左子節點,右子節點
一般情況下我們使用遞歸算法對二叉樹進行遍歷:先序遍歷,中序遍歷,後序遍歷
先序遍歷
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
分析如下:
1.首先輸出首節點12的值
2.一直遞歸對左右子節點進行相同操作,總是完成左子節點的遍歷再進行右子節點的遍歷
3.重複2直至節點爲空,然後一步一步向上返回。
先序遍歷:12 24 40 56 55 50 35 66 70
- 中序遍歷
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
中序遍歷:56 40 55 24 50 12 66 35 70
- 後續遍歷
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
後序遍歷:56 55 40 50 24 66 70 35 12