Jan 28 - Convert Sorted Array Into Height-Balanced BST; BFS; DAC; Tree; Array;

We can use DAC to build a height balanced BST, in a block of array from low to high, if low == high we are finding one node, just add it.

if low == high-1, we have two choice, here we only create a new node of nums[low] value and set its right child node to the next node(low+1, high).

Otherwise, mid = (low+high)/2. A new node of value nums[mid], and set its left child node to be the next node(low, mid-1) and the right child node to be the next node in the range of (mid+1, high).

Code:

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

 

你可能感兴趣的:(Jan 28 - Convert Sorted Array Into Height-Balanced BST; BFS; DAC; Tree; Array;)