首页 > 代码库 > [LeetCode]108 Convert Sorted Array to Binary Search Tree
[LeetCode]108 Convert Sorted Array to Binary Search Tree
https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
http://fisherlei.blogspot.com/2013/03/leetcode-convert-sorted-array-to-binary.html
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { // O(log n) public TreeNode sortedArrayToBST(int[] num) { // 要求为一个 height balanced BST. // 如果没有这个要求,一个list (永远只有右节点)即满足要求 // // 每次取中间点未新的root TreeNode root = build(num, 0, num.length - 1); return root; } private TreeNode build(int[] num, int low, int high) { if (low > high) return null; if (low == high) return new TreeNode(num[low]); int mid = (low + high) / 2; TreeNode node = new TreeNode(num[mid]); node.left = build(num, low, mid - 1); node.right = build(num, mid + 1, high); return node; } }
[LeetCode]108 Convert Sorted Array to Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。