各位讀者週末愉快呀,今天我想來說說一道很常見的面試題目 —— 關於二叉樹前中後序遍歷的實現。本文將以遞歸和非遞歸方式實現這 3 種遍歷方式,代碼都比較短,可以放心食用。
先簡單說明一下這 3 種遍歷方式有什麼不同 —— 對於每種遍歷,樹中每個結點都需要經過 3 次(對於葉結點,其左右子樹視爲空子樹),但前序遍歷在第一次遇到結點時就立即訪問,中序遍歷是在第二次遇到結點時訪問,後序遍歷則是第三次訪問。
所以前中後序遍歷訪問結點的順序分別是中左右、左中右、左右中。「中」表示當前結點,「左右」表示當前結點的左右子樹。
下面讓我們一起來看下代碼是怎麼實現的吧。
遞歸版
前序遍歷
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
中序遍歷
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
後序遍歷
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
非遞歸版
前序遍歷
public static void preOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.print(head.value + " ");
if (head.right != null) {
stack.push(head.right);
}
if (head.left != null) {
stack.push(head.left);
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
中序遍歷
public static void inOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
後序遍歷
public static void posOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while (!s1.isEmpty()) {
head = s1.pop();
s2.push(head);
if (head.left != null) {
s1.push(head.left);
}
if (head.right != null) {
s1.push(head.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
以上就是二叉樹的 3 種遍歷方式,你學會了嗎?
PS:本文原創發佈於微信公衆號「不只Java」,後臺回覆「Java」,送你 13 本 Java 經典電子書。公衆號專注分享 Java 乾貨、讀書筆記、成長思考。
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-095d4a0b23.css" rel="stylesheet">
</div>