java数组实现二叉树
时间: 2023-11-24 12:06:56 浏览: 84
以下是Java数组实现二叉树的示例代码:
```java
public class BinaryTree {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public static TreeNode createBinaryTree(Integer[] array, int index) {
TreeNode treeNode = null;
if (index < array.length) {
Integer value = array[index];
if (value == null) {
return null;
}
treeNode = new TreeNode(value);
treeNode.left = createBinaryTree(array, 2 * index + 1);
treeNode.right = createBinaryTree(array, 2 * index + 2);
return treeNode;
}
return treeNode;
}
public static void main(String[] args) {
Integer[] array = {1, 7, 8, 3, 5, null, null};
TreeNode root = createBinaryTree(array, 0);
System.out.println(root.val); // 输出:1
System.out.println(root.left.val); // 输出:7
System.out.println(root.right.val); // 输出:8
}
}
```
阅读全文