【二叉树】先序序列创建二叉树,输出先序序列、中序序列、后序序列并输出叶子结点数 (java) 代码
时间: 2024-11-23 12:40:58 浏览: 8
建立二叉树,并输出二叉树的先序,中序和后序遍历序列,以及二叉树的叶子数
在Java中,我们可以使用递归的方式来创建二叉树并生成其先序、中序和后序序列。下面是一个简单的示例代码,它首先定义了一个二叉树节点类`TreeNode`,然后提供了一个函数`buildTreePreInPost`来构建树并获取序列:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class BinaryTree {
public static void main(String[] args) {
// 先序序列示例 [1, 2, 4, 7, 3, 6, 5]
int[] preOrder = {1, 2, 4, 7, 3, 6, 5};
TreeNode root = buildTreePreInPost(preOrder, 0);
// 输出先序、中序和后序序列
System.out.println("先序遍历: " + printPreOrder(root));
System.out.println("中序遍历: " + printInOrder(root));
System.out.println("后序遍历: " + printPostOrder(root));
// 计算叶子节点数
int leafCount = countLeaves(root);
System.out.println("叶子节点数: " + leafCount);
}
public static TreeNode buildTreePreInPost(int[] preorder, int index) {
if (index == preorder.length) return null;
TreeNode node = new TreeNode(preorder[index]);
int i = findInPostIndex(preorder, index);
node.left = buildTreePreInPost(preorder, index + 1); // 左孩子
node.right = buildTreePreInPost(preorder, i); // 右孩子
return node;
}
private static int findInPostIndex(int[] inorder, int preorderIndex) {
for (int i = 0; i < inorder.length; i++) {
if (inorder[i] == preorder[preorderIndex]) {
return i + 1; // 中序下标从1开始
}
}
return -1;
}
// 递归遍历方法
private static String printPreOrder(TreeNode node) {
if (node == null) return "";
return node.val + " " + printPreOrder(node.left) + printPreOrder(node.right);
}
private static String printInOrder(TreeNode node) {
if (node == null) return "";
return printInOrder(node.left) + node.val + " " + printInOrder(node.right);
}
private static String printPostOrder(TreeNode node) {
if (node == null) return "";
return printPostOrder(node.left) + printPostOrder(node.right) + node.val;
}
private static int countLeaves(TreeNode node) {
if (node == null) return 0;
if (node.left == null && node.right == null) return 1; // 如果左右都是null,则是叶子节点
return countLeaves(node.left) + countLeaves(node.right);
}
}
```
这个程序首先根据给定的先序遍历序列构建了二叉树,然后分别计算并输出了三种遍历序列以及叶子节点的数量。
阅读全文