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

108. Convert Sorted Array to Binary Search Tree

时间:2019-04-04 14:25:49      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:sort   array   color   int   root   start   imp   EDA   one   

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

标签:sort   array   color   int   root   start   imp   EDA   one   

原文地址:https://www.cnblogs.com/chucklu/p/10654437.html

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