LeetCode(108)——Convert Sorted Array to Binary Search Tree

題目:

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

利用二叉搜索樹和排序數組的關係,由於要求高度平衡的,那麼可以把數組的左右兩邊分別作爲高度平衡的二叉樹,中間作爲根節點即可,遞歸求解。

AC:

public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null) {
            return null;
        }
        
        return helper(nums, 0, nums.length - 1);
    }
    
    private TreeNode helper(int[] nums, int begin, int end) {
        if (begin > end) {
            return null;
        }
        
        if (begin == end) {
            return new TreeNode(nums[begin]);
        }
        
        int mid = (begin + end) >> 1;
        
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, begin, mid - 1);
        root.right = helper(nums, mid + 1, end);
        return root;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章