108. Convert Sorted Array to Binary Search Tree

Posted chucklu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了108. Convert Sorted Array to Binary Search Tree相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/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

https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/

Following is a simple algorithm where we first find the middle node of list and make it root of the tree to be constructed.

1) Get the Middle of the array and make it root.
2) Recursively do same for left half and right half.
      a) Get the middle of left half and make it left child of the root
          created in step 1.
      b) Get the middle of right half and make it right child of the
          root created in step 1.

找到中间的结点,作为root。也就是0。

左边是-10,-3。右边是5,9。

-10和-3对应的index是0,1

 

  public TreeNode SortedArrayToBST(int[] nums)
        {
            return SortedArrayToBST(nums, 0, nums.Length - 1);
        }

        public TreeNode SortedArrayToBST(int[] arr, int start, int end)
        {
            if (start > end)
            {
                return null;
            }

            int mid = (start + end) / 2;
            TreeNode node = new TreeNode(arr[mid]);
            node.left = SortedArrayToBST(arr, start, mid - 1);
            node.right = SortedArrayToBST(arr, mid + 1, end);
            return node;
        }

 

以上是关于108. Convert Sorted Array to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

leetcode 108 Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

LC.108.Convert Sorted Array to Binary Search Tree