天天看点

LeetCode刷题笔录Convert Sorted Array to Balanced Binary Search Tree

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

这题可以一眼看出是要用递归,不会是叫你写一个BST的插入。每次选出sorted array中间的那个元素作为当前的node,这个node的左儿子是左半边数组的中间元素,右儿子是右半边数组的中间元素。这样就有Subproblem了。

coding的时候注意subproblem的范围是(low, mid - 1)和(mid + 1, high),因为mid元素已经用过了。

发现自己递归还是要多练练,想到了这是递归也用了很久才写出代码,sigh

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        return helper(num, 0, num.length - 1);
    }
    public TreeNode helper(int[] num, int low, int high){
        if(low > high)
            return null;
        int mid = (low + high) / 2;
        
        TreeNode node = new TreeNode(num[mid]);
        node.left = helper(num, low, mid - 1);
        node.right = helper(num, mid + 1, high);
        return node;
            
    }
}