首页 > 代码库 > 【LeetCode题目记录-9】排序后的数组生成平衡的二叉搜索树

【LeetCode题目记录-9】排序后的数组生成平衡的二叉搜索树

Convert Sorted Array to Binary Search Tree

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

【分析1-原创】中间值作为根节点,左边的中间值作为左孩子,右边的中间值作为右孩子。一直递归探底即可。

/**
 * 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) {
        if(num==null) return null;
        //获取中间的值作为根节点
        TreeNode root=getMiddle(num,0,num.length-1);
        if(num.length==1) return root;
        //递归调用
        arrayToBST(num,0,num.length-1,root);
        return root;
    }
    private void arrayToBST(int[] num,int start,int end,TreeNode node){
        if(start>end) return;
        int middle=(start+end)>>1;
        node.left=getMiddle(num,start,middle-1);
        node.right=getMiddle(num,middle+1,end);
        arrayToBST(num,start,middle-1,node.left);
        arrayToBST(num,middle+1,end,node.right);
    }
    //获取中间的值作为节点
    private TreeNode getMiddle(int[] num,int start,int end){
        if(start>end) return null;
        return new TreeNode(num[(start+end)>>1]);
    }
   
}


【分析2-非原创】更简洁的写法。

https://oj.leetcode.com/discuss/6248/why-it-shows-runtime-error-when-using-my-recursive-code

 

 /**
     * 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 arrayToBST(num, 0, num.length - 1);
        }
 
        private TreeNode arrayToBST(int[] num, int start, int end) {
            if (start > end)
                return null;
            int middle = start + (end - start >> 1);
            TreeNode root = new TreeNode(num[middle]);
            if (start != end) {
                root.left = arrayToBST(num, start, middle - 1);
                root.right = arrayToBST(num, middle + 1, end);
            }
            return root;
        }
    }

   

【LeetCode题目记录-9】排序后的数组生成平衡的二叉搜索树