[LeetCode] 108. converting into an ordered array of binary search trees

Topic links: https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/

Subject description:

An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.

In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.

Example:

给定有序数组: [-10,-3,0,5,9],

一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:

      0
      / \
    -3   9
   /   /
 -10  5

Ideas:

We find the midpoint of the array, and then divided into two parts,

For example [-10,-3,0,5,9], a node 0on the left of [-10, -3]the right[5, 9]

Turn recursion.

Code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if not nums: return 
        mid = len(nums) // 2
        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])
        return root

java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0) return null;
        return helper(nums, 0, nums.length - 1);
    }

    private TreeNode helper(int[] nums, int left, int high) {
        if (left > high) return null;
        int mid = left + (high - left) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, high);
        return root;
    }
}

Guess you like

Origin www.cnblogs.com/powercai/p/11104603.html