实验目的:掌握二叉树的构建及遍历操作。 实验内容:按先序遍历的顺序构建的二叉树实现先序、中序和后序遍历,并输出对应的遍历序列,节点要用字母表示。 实验要求: 1、构建一个二叉链表存储结构的二叉树。 2、基于上述构建的二叉树进行先序、中序和后序遍历操作。用Java实现
时间: 2023-11-22 13:54:07 浏览: 40
Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例
以下是Java代码实现:
```java
public class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char x) { val = x; }
}
public class BinaryTree {
public TreeNode buildTree(char[] preorder, char[] inorder) {
if (preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0)
return null;
return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
private TreeNode build(char[] preorder, int preStart, int preEnd, char[] inorder, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd)
return null;
char rootVal = preorder[preStart];
TreeNode root = new TreeNode(rootVal);
int index = findIndex(inorder, rootVal, inStart, inEnd);
int leftSize = index - inStart;
root.left = build(preorder, preStart + 1, preStart + leftSize, inorder, inStart, index - 1);
root.right = build(preorder, preStart + leftSize + 1, preEnd, inorder, index + 1, inEnd);
return root;
}
private int findIndex(char[] inorder, char val, int start, int end) {
for (int i = start; i <= end; i++) {
if (inorder[i] == val)
return i;
}
return -1;
}
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) {
BinaryTree tree = new BinaryTree();
char[] preorder = {'A', 'B', 'D', 'E', 'C', 'F'};
char[] inorder = {'D', 'B', 'E', 'A', 'F', 'C'};
TreeNode root = tree.buildTree(preorder, inorder);
System.out.print("先序遍历结果:");
tree.preorder(root);
System.out.print("\n中序遍历结果:");
tree.inorder(root);
System.out.print("\n后序遍历结果:");
tree.postorder(root);
}
}
```
输出结果:
```
先序遍历结果:A B D E C F
中序遍历结果:D B E A F C
后序遍历结果:D E B F C A
```
阅读全文