使用java写一个构造平衡二叉树的代码
时间: 2023-05-25 16:07:05 浏览: 47
```
public class Node {
int val;
Node left;
Node right;
Node(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class BalancedBinaryTree {
public Node createBalancedTree(int[] arr, int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end) / 2;
Node root = new Node(arr[mid]);
root.left = createBalancedTree(arr, start, mid - 1);
root.right = createBalancedTree(arr, mid + 1, end);
return root;
}
}
// 测试代码
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
BalancedBinaryTree tree = new BalancedBinaryTree();
Node root = tree.createBalancedTree(arr, 0, arr.length - 1);
// 对 root 进行遍历并输出结果
}
```