4.3
来源:互联网 发布:魔客吧还原数据密码 编辑:程序博客网 时间:2024/06/08 04:32
Topic:Given a sorted (increasing order) array, write an algorithm to create a binary search tree with minimal height.
public class TreeNode { public int data; public TreeNode left; public TreeNode right; public TreeNode parent; public TreeNode(int data) { this.data = data; } public void setLeftChild(TreeNode left) { this.left = left; if (left != null) { left.parent = this;//设了left,同时相应的要设parent } } public void setRightChild(TreeNode right) { this.right = right; if (right != null) { right.parent = this; } } public static TreeNode createMinimalBST(int arr[], int start, int end){//因为从上往下递归构造BST需要不断把数组折半,所以需要头尾参数,所以该方法分两步来写 if (end < start) {return null;} int mid = (start + end) / 2;TreeNode n = new TreeNode(arr[mid]);n.setLeftChild(createMinimalBST(arr, start, mid - 1));n.setRightChild(createMinimalBST(arr, mid + 1, end));return n; } public static TreeNode createMinimalBST(int array[]){ return createMinimalBST(array, 0, array.length - 1); } public int height1() { int leftHeight = left != null ? left.height1() : 0;int rightHeight = right != null ? right.height1() : 0;return 1 + Math.max(leftHeight, rightHeight); }}
public class CC { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TreeNode root1 = TreeNode.createMinimalBST(array);//调用的是TreeNode类的方法,所以TreeNode. System.out.println(root1.height1()); System.out.println(root1.data); /* 5 2 8 1 3 6 9 4 7 10*/ }}
//结果45
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3
- 4.3 4.4
- 日志 4.3
- CareerCup-4.3
- CareerCup 4.3
- 4.3Composite
- exercise 4.3
- 4.3E2
- 黑马程序员——Java1.6新特性
- 黑马程序员——Java26中设计模式
- 关于Android静态注册BroadCast
- 4.2
- VB 字符串函数
- 4.3
- 4.4
- Exchange 2000 Server安装部署与设置
- [细胞生命进化理论]关于基因文明的演化道路的一些思考
- ELF文件格式分析
- 黑马程序员-我的入学笔记2-关于类
- Ubuntu下vim中ctags的配置方法
- 我是如何开发一个连锁企业的信息系统的,NO.3
- 需求,自己的?大家的?