[LeetCode]108. Convert Sorted Array to Binary Search Tree

来源:互联网 发布:餐饮收银软件多少钱 编辑:程序博客网 时间:2024/06/05 11:33

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

是一道比较简单的递归题。
像二分查找一样,不断地把升序数组切半,分别看做新的数组,再切半。。。
这边要注意:如果low > high,  返回空结点。

   public TreeNode buildTree(int[] num, int low, int high){         if(low>high)              return null;                   int mid = low+(high-low)/2;         TreeNode node = new TreeNode(num[mid]);         node.left = buildTree(num,low,mid-1);         node.right = buildTree(num,mid+1,high);         return node;   }   public TreeNode sortedArrayToBST(int[] num) {         return buildTree(num,0,num.length-1);   }

  


0 0