码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-15 17:47:49      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:排序后的数组生成平衡的二叉搜索树

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】排序后的数组生成平衡的二叉搜索树

标签:排序后的数组生成平衡的二叉搜索树

原文地址:http://blog.csdn.net/brillianteagle/article/details/39295147

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!