這棵樹

- 前序遍歷:5 5 3 9 1 7 6 2 4 1
- 中序遍歷:9 3 1 5 5 2 6 4 7 1
- 後序遍歷:9 1 3 5 2 4 6 1 7 5
- 層次遍歷:5 5 7 3 6 1 9 1 2 4
前序遍歷
遞歸實現
// 前序遍歷(遞歸)
public static void preOrder(BinaryTree bt) {
if (null != root) {
System.out.print(bt.val + " ");
preOrder(bt.left);
preOrder(bt.right);
}
}
非遞歸實現
- 利用棧,每次根節點入棧以後出棧,再依次將右子樹節點和左子樹節點入棧,直到棧空。
// 前序遍歷(非遞歸:利用棧)
public static void preOrder1(BinaryTree bt) {
if (bt != null) {
Stack<BinaryTree> tmp = new Stack<>();
tmp.push(bt);
while (!tmp.isEmpty()) {
BinaryTree b = tmp.pop();
System.out.print(b.val + " ");
// 注意:先將右子樹孩子壓入棧,再將左子樹壓入棧
if (b.right != null) {
tmp.push(b.right);
}
if (b.left != null) {
tmp.push(b.left);
}
}
}
}
中序遍歷
遞歸實現
// 中序遍歷(遞歸)
public static void inOrder(BinaryTree bt) {
if (bt != null) {
inOrder(bt.left);
System.out.print(bt.val + " ");
inOrder(bt.right);
}
}
非遞歸實現
後序遍歷
遞歸實現
// 後序遍歷(遞歸)
public static void postOrder(BinaryTree bt) {
if (bt != null) {
postOrder(bt.left);
postOrder(bt.right);
System.out.print(bt.val + " ");
}
}
非遞歸實現
層次遍歷
// 層次遍歷
public static void levelOrder(BinaryTree bt) {
if (bt != null) {
Queue<BinaryTree> tmp = new LinkedList<>();
tmp.add(bt);
while (!tmp.isEmpty()) {
BinaryTree b = tmp.poll();
System.out.print(b.val + " ");
if (b.left != null) {
tmp.add(b.left);
}
if (b.right != null) {
tmp.add(b.right);
}
}
}
}