• 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
    


     

    Appraoch #1: C++.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            if (nums.size() == 0) return nullptr;
            if (nums.size() == 1) return new TreeNode(nums[0]);
            
            int mid = nums.size() / 2;
            TreeNode* root = new TreeNode(nums[mid]);
            
            vector<int> leftNums(nums.begin(), nums.begin()+mid);
            vector<int> rightNums(nums.begin()+mid+1, nums.end());
            
            root->left = sortedArrayToBST(leftNums);
            root->right = sortedArrayToBST(rightNums);
            
            return root;
        }
    };
    

      

    Approach #2: Java.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            if (nums.length < 1)
                return null;
            TreeNode head = helper(nums, 0, nums.length-1);
            return head;
        }
        
        private TreeNode helper(int[] nums, int low, int height) {
            if (low > height) return null;
            int mid = (low + height) / 2;
            TreeNode node = new TreeNode(nums[mid]);
            node.left = helper(nums, low, mid-1);
            node.right = helper(nums, mid+1, height);
            return node;
        }
            
    }
    

      

    Approach #3: Python.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            if len(nums) == 0:
                return None
            
            mid = len(nums) / 2
            root = TreeNode(nums[mid])
            
            root.left = self.sortedArrayToBST(nums[:mid])
            root.right = self.sortedArrayToBST(nums[mid+1:])
            
            return root
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Git 最全命令使用
    git 配置(实用)
    用Redis进行实时数据排名
    最长上升子序列
    KMP算法
    计算星期几【基姆拉尔森公式】
    集合划分(贝尔数)
    合数分解(质因数分解)
    乘法逆元
    扩展欧几里得算法
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10026638.html
Copyright © 2020-2023  润新知