美文网首页
LeetCode实战:将有序数组转换为二叉搜索树

LeetCode实战:将有序数组转换为二叉搜索树

作者: 老马的程序人生 | 来源:发表于2019-06-18 17:31 被阅读0次

    题目英文

    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.

    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
    

    题目中文

    将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

    本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

    示例:

    给定有序数组: [-10,-3,0,5,9],
    
    一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
    
          0
         / \
       -3   9
       /   /
     -10  5
    

    算法实现

    /**
     * Definition for a binary tree node.
     * public class TreeNode 
     * {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
     
    public class Solution
    {
        public TreeNode SortedArrayToBST(int[] nums)
        {
            return nums == null ? null : BuildTree(nums, 0, nums.Length - 1);
        }
    
        private TreeNode BuildTree(int[] nums, int left, int right)
        {
            if (left > right)
                return null;
            int mid = left + (right - left)/2;
            TreeNode root = new TreeNode(nums[mid]);
            root.left = BuildTree(nums, left, mid - 1);
            root.right = BuildTree(nums, mid + 1, right);
            return root;
        }
    }
    

    实验结果

    提交记录

    <b>测试用例</b>:

    输入:[-10,-3,0,5,9]
    输出:[0,-10,5,null,-3,null,9]
    
    输入:[]
    输出:[]
    
    输入:[0,1,2,3,4,5]
    输出:[2,0,4,null,1,3,5]
    

    相关图文

    相关文章

      网友评论

          本文标题:LeetCode实战:将有序数组转换为二叉搜索树

          本文链接:https://www.haomeiwen.com/subject/xwhqqctx.html