首页 > 代码库 > [LeetCode]108 Convert Sorted Array to Binary Search Tree

[LeetCode]108 Convert Sorted Array to Binary Search Tree

https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

http://fisherlei.blogspot.com/2013/03/leetcode-convert-sorted-array-to-binary.html


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    // O(log n)
    public TreeNode sortedArrayToBST(int[] num) {
        
        // 要求为一个 height balanced BST.
        // 如果没有这个要求,一个list (永远只有右节点)即满足要求
        //
        // 每次取中间点未新的root
        TreeNode root = build(num, 0, num.length - 1);
        return root;
    }
    
    private TreeNode build(int[] num, int low, int high)
    {
        if (low > high)
            return null;
        
        if (low == high)
            return new TreeNode(num[low]);
            
        int mid = (low + high) / 2;
        TreeNode node = new TreeNode(num[mid]);
        node.left = build(num, low, mid - 1);
        node.right = build(num, mid + 1, high);
        return node;
    }
}


[LeetCode]108 Convert Sorted Array to Binary Search Tree