2
头图

Convert an ordered array to a binary search tree

Title description: Give you an integer array nums, in which the elements have been arranged in ascending order, please convert it into a highly balanced binary search tree.

A height-balanced binary tree is a binary tree that satisfies "the absolute value of the height difference between the left and right subtrees of each node does not exceed 1".

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Recursion

According to the nature of the binary search tree, because the given array is arranged in ascending order, it can be determined that the array num is the middle-order traversal sequence of the binary search tree. In order to obtain a balanced binary tree, take the middle position of the array The node serves as the root node, so that the nodes of the left and right subtrees are more balanced. The specific processing process is as follows:

  • Call the recursive method, the initial starting position is the length of the array;
  • When the start position is greater than the end position, the node has been traversed, and the empty tree is returned directly;
  • Obtain the value of the middle position as the root node, so that the node tree of the left and right subtrees is more balanced;
  • Then recursively obtain the left and right subtrees of the current root node;
  • Finally, the root node is returned to the balanced binary search tree.
import com.kaesar.leetcode.TreeNode;

public class LeetCode_108 {
    public static TreeNode sortedArrayToBST(int[] nums) {
        // 调用递归方法,初始的起始位置为数组的长度
        return sortedArrayToBST(nums, 0, nums.length - 1);
    }

    /**
     * 递归
     *
     * @param nums
     * @param left
     * @param right
     * @return
     */
    private static TreeNode sortedArrayToBST(int[] nums, int left, int right) {
        // 当起点位置大于终点位置时,说明节点已经遍历完了,直接返回空树
        if (left > right) {
            return null;
        }
        // 获取中间位置的值作为根节点,这样左右子树的节点树是较为平衡点
        int mid = (left + right) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        // 然后递归获得当前根节点的左右子树
        root.left = sortedArrayToBST(nums, left, mid - 1);
        root.right = sortedArrayToBST(nums, mid + 1, right);
        return root;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-10, -3, 0, 5, 9};
        sortedArrayToBST(nums).print();
    }
}
【Daily Message】 live up to every morning sun, will not waste every late night, struggle because of the ordinary, and be extraordinary because of struggle.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!