实验目的:掌握二叉树的构建及遍历操作。 实验内容:按先序遍历的顺序为“ABDGCEF”构建的二叉树实现先序、中序和后序遍历,并输出对应的遍历序列。 实验要求: 1、构建一个二叉链表存储结构的二叉树。 2、基于上述构建的二叉树进行先序、中序和后序遍历操作。用Java实现
时间: 2023-11-22 11:54:02 浏览: 101
以下是Java实现的代码示例:
```java
// 定义二叉树节点类
class TreeNode {
char val;
TreeNode left;
TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
// 构建二叉树
class BinaryTree {
public TreeNode buildTree(char[] preorder, int preIndex, int inStart, int inEnd) {
if (preIndex >= preorder.length || inStart > inEnd)
return null;
// 构建根节点
TreeNode root = new TreeNode(preorder[preIndex]);
// 在中序遍历中找到根节点的位置
int inIndex = inStart;
while (inIndex <= inEnd && preorder[preIndex] != inorder[inIndex])
inIndex++;
// 递归构建左右子树
root.left = buildTree(preorder, preIndex + 1, inStart, inIndex - 1);
root.right = buildTree(preorder, preIndex + inIndex - inStart + 1, inIndex + 1, inEnd);
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 class Main {
public static void main(String[] args) {
char[] preorder = {'A', 'B', 'D', 'G', 'C', 'E', 'F'};
BinaryTree binaryTree = new BinaryTree();
TreeNode root = binaryTree.buildTree(preorder, 0, 0, preorder.length - 1);
System.out.print("先序遍历:");
binaryTree.preOrder(root);
System.out.print("\n中序遍历:");
binaryTree.inOrder(root);
System.out.print("\n后序遍历:");
binaryTree.postOrder(root);
}
}
```
输出结果:
```
先序遍历:A B D G C E F
中序遍历:G D B A E C F
后序遍历:G D B E F C A
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)