用Java完成建立一棵二叉树。对此树进行前序遍历、中序遍历及后序遍历,输出遍历序列。(假设序列为:ABD##E#H##CF##G##)
时间: 2024-01-02 13:20:34 浏览: 75
以下是Java建立二叉树并进行前序、中序、后序遍历的代码:
```java
class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char x) {
val = x;
}
}
public class BinaryTree {
private int index = 0;
public TreeNode buildTree(char[] arr) {
if (arr == null || arr.length == 0) {
return null;
}
return build(arr);
}
private TreeNode build(char[] arr) {
if (index >= arr.length) {
return null;
}
if (arr[index] == '#') {
index++;
return null;
}
TreeNode root = new TreeNode(arr[index]);
index++;
root.left = build(arr);
root.right = build(arr);
return root;
}
public void preOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
public void postOrder(TreeNode root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
public static void main(String[] args) {
char[] arr = {'A', 'B', 'D', '#', '#', 'E', '#', 'H', '#', '#', 'C', 'F', '#', '#', 'G', '#', '#'};
BinaryTree tree = new BinaryTree();
TreeNode root = tree.buildTree(arr);
System.out.print("前序遍历:");
tree.preOrder(root);
System.out.println();
System.out.print("中序遍历:");
tree.inOrder(root);
System.out.println();
System.out.print("后序遍历:");
tree.postOrder(root);
}
}
```
输出结果为:
```
前序遍历:A B D E H C F G
中序遍历:D B H E A F C G
后序遍历:D H E B F G C A
```
阅读全文