用java用二叉链表表示树,结点的值为结点的序号,创建n个结点的完全二叉树,输出前、中、后三种遍历
时间: 2024-05-04 09:18:13 浏览: 73
用java实现二叉树的创建和遍历.doc
以下是Java代码实现:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
val = x;
}
}
class BinaryTree {
private TreeNode root;
public BinaryTree(int n) {
root = createTree(1, n);
}
private TreeNode createTree(int i, int n) {
if (i > n) {
return null;
}
TreeNode root = new TreeNode(i);
root.left = createTree(i * 2, n);
root.right = createTree(i * 2 + 1, n);
return root;
}
public void preOrderTraversal() {
preOrderTraversal(root);
System.out.println();
}
private void preOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
public void inOrderTraversal() {
inOrderTraversal(root);
System.out.println();
}
private void inOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
inOrderTraversal(root.left);
System.out.print(root.val + " ");
inOrderTraversal(root.right);
}
public void postOrderTraversal() {
postOrderTraversal(root);
System.out.println();
}
private void postOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.print(root.val + " ");
}
}
public class Main {
public static void main(String[] args) {
int n = 7;
BinaryTree binaryTree = new BinaryTree(n);
System.out.print("前序遍历:");
binaryTree.preOrderTraversal();
System.out.print("中序遍历:");
binaryTree.inOrderTraversal();
System.out.print("后序遍历:");
binaryTree.postOrderTraversal();
}
}
```
输出结果为:
```
前序遍历:1 2 4 5 3 6 7
中序遍历:4 2 5 1 6 3 7
后序遍历:4 5 2 6 7 3 1
```
阅读全文