【二叉树】先序序列创建二叉树,输出先序序列、中序序列、后序序列并输出叶子结点数 (java)
时间: 2024-11-22 20:46:49 浏览: 1
在Java中,我们可以使用递归的方式来创建二叉树并计算先序、中序和后序遍历以及叶子节点的数量。下面是一个简单的例子:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeTraversal {
public static void main(String[] args) {
// 先序序列示例:[1, 2, 4, 5, 3]
String preorder = "1,2,4,5,3";
// 创建根节点,并构建整棵树
TreeNode root = buildTree(preorder.split(","), 0);
// 计算并打印结果
System.out.println("先序遍历: " + inOrder(root));
System.out.println("中序遍历: " + preOrder(root));
System.out.println("后序遍历: " + postOrder(root));
System.out.println("叶子节点数: " + countLeaves(root));
}
private static TreeNode buildTree(String[] preorder, int index) {
if (index == preorder.length) return null;
TreeNode node = new TreeNode(Integer.parseInt(preorder[index]));
int mid = findMid(preorder, index);
node.left = buildTree(preorder, index + 1);
node.right = buildTree(preorder, mid);
return node;
}
private static int findMid(String[] preorder, int index) {
// 中序遍历的查找,假设中序是有序的
for (int i = index; i < preorder.length; i++) {
if (preorder[i].equals(preorder[index])) break;
}
return i;
}
private static String inOrder(TreeNode node) {
StringBuilder sb = new StringBuilder();
if (node != null) {
sb.append(inOrder(node.left));
sb.append(node.val).append(",");
sb.append(inOrder(node.right));
}
return sb.toString().trim(); // 去除末尾逗号
}
private static String preOrder(TreeNode node) {
StringBuilder sb = new StringBuilder();
if (node != null) {
sb.append(node.val).append(",");
sb.append(preOrder(node.left));
sb.append(preOrder(node.right));
}
return sb.toString().trim(); // 去除末尾逗号
}
private static String postOrder(TreeNode node) {
StringBuilder sb = new StringBuilder();
if (node != null) {
sb.append(postOrder(node.left));
sb.append(postOrder(node.right));
sb.append(node.val).append(",");
}
return sb.toString().trim(); // 去除末尾逗号
}
private static int countLeaves(TreeNode node) {
if (node == null) return 0;
if (node.left == null && node.right == null) return 1;
return countLeaves(node.left) + countLeaves(node.right);
}
}
```
这个程序首先通过先序序列创建二叉树,然后分别进行中序、前序和后序遍历,并计算叶子节点的数量。注意这里假设输入的先序序列是正确的,如果实际操作中需要处理错误输入,还需要添加相应的错误检查和处理机制。
阅读全文