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




 

原创粉丝点击