PTA二叉树的遍历java
时间: 2023-12-22 13:29:33 浏览: 97
以下是PTA二叉树的遍历的Java代码示例:
```java
import java.util.Scanner;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class BinaryTreeTraversal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
TreeNode[] nodes = new TreeNode[n];
for (int i = 0; i < n; i++) {
nodes[i] = new TreeNode(sc.nextInt());
}
for (int i = 0; i < n; i++) {
int leftIndex = sc.nextInt();
int rightIndex = sc.nextInt();
if (leftIndex != -1) {
nodes[i].left = nodes[leftIndex];
}
if (rightIndex != -1) {
nodes[i].right = nodes[rightIndex];
}
}
sc.close();
System.out.print("Preorder traversal: ");
preorderTraversal(nodes[0]);
System.out.println();
System.out.print("Inorder traversal: ");
inorderTraversal(nodes[0]);
System.out.println();
System.out.print("Postorder traversal: ");
postorderTraversal(nodes[0]);
System.out.println();
}
public static void preorderTraversal(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
public static void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
inorderTraversal(root.left);
System.out.print(root.val + " ");
inorderTraversal(root.right);
}
public static void postorderTraversal(TreeNode root) {
if (root == null) {
return;
}
postorderTraversal(root.left);
postorderTraversal(root.right);
System.out.print(root.val + " ");
}
}
```
阅读全文