-
前序遍历(Preorder Traversal):
-
访问根节点
-
前序遍历左子树
-
前序遍历右子树
-
-
中序遍历(Inorder Traversal):
-
中序遍历左子树
-
访问根节点
-
中序遍历右子树
-
-
后序遍历(Postorder Traversal):
-
后序遍历左子树
-
后序遍历右子树
-
访问根节点
-
-
层序遍历(Level Order Traversal):
-
按层次逐层遍历,从根节点开始,一层一层向下遍历
-
下面是每种遍历方式的 Java 实现:
前序遍历(Preorder Traversal)
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class BinaryTree {
public void preorderTraversal(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
}
中序遍历(Inorder Traversal)
public class BinaryTree {
public void postorderTraversal(TreeNode root) {
if (root == null) {
return;
}
postorderTraversal(root.left);
postorderTraversal(root.right);
System.out.print(root.val + " ");
}
}
后序遍历(Postorder Traversal)
public class BinaryTree {
public void postorderTraversal(TreeNode root) {
if (root == null) {
return;
}
postorderTraversal(root.left);
postorderTraversal(root.right);
System.out.print(root.val + " ");
}
}
层序遍历(Level Order Traversal)
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree {
public void levelOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.print(node.val + " ");
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
}