Leetcode108. 将有序数组转换为二叉搜索树
因为数组是有序的,可以递归的选取根节点构建子树。
JAVA:
public final TreeNode sortedArrayToBST(int[] nums) { if (null == nums) return null; return this.build(nums, 0, nums.length - 1); } private TreeNode build(int[] nums, int left, int right) { if (left > right) return null; if (left == right) return new TreeNode(nums[left]); int mid = (left + right) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = build(nums, left, mid - 1); root.right = build(nums, mid + 1, right); return root; }
JS:
var sortedArrayToBST = function (nums) { if (!nums) return null; return build(nums, 0, nums.length - 1); }; var build = function (nums, left, right) { if (left > right) return null; if (left == right) return new TreeNode(nums[left]); let mid = Math.floor((left + right) / 2); let root = new TreeNode(nums[mid]); root.left = build(nums, left, mid - 1); root.right = build(nums, mid + 1, right); return root; }
C:
struct TreeNode *build(int *nums, int numsSize, int left, int right) { if (left > right) return NULL; if (left == right) { struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); node->val = nums[left]; node->left = NULL; node->right = NULL; return node; } int mid = (left + right) / 2; struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode)); root->val = nums[mid]; root->left = build(nums, numsSize, left, mid - 1); root->right = build(nums, numsSize, mid + 1, right); return root; } struct TreeNode *sortedArrayToBST(int *nums, int numsSize) { struct TreeNode *root = build(nums, numsSize, 0, numsSize - 1); return root; }
Python3:
class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: return self.build(nums, 0, len(nums) - 1) def build(self, nums: List[int], left: int, right: int) -> Optional[TreeNode]: if left > right: return None if left == right: return TreeNode(nums[left]) mid = (left + right) // 2 root = TreeNode(nums[mid]) root.left = self.build(nums, left, mid - 1) root.right = self.build(nums, mid + 1, right) return root
当你看清人们的真相,于是你知道了,你可以忍受孤独