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。

====================

0.left = SortedArrayToBST(arr, 0, 1)

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

 

node=array[0];也就是-10。所以0.left=-10;

 

 

 

  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;
        }

 

posted @ 2019-04-04 13:51  ChuckLu  阅读(138)  评论(0编辑  收藏  举报