Programmer Interview Golden Code-Interview Questions 04.02. Minimum Height Tree

1. Topic introduction

Given an ordered array of integers with different elements and arranged in ascending order, write an algorithm to create a binary search tree with the smallest height.

Example:
Given an ordered array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which can represent the following highly balanced binary search tree:

          0 
         / \ 
       -3   9 
       /   / 
     -10  5 

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/minimum-height-tree-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

        The characteristics that the minimum height tree satisfies: the height difference between the left and right subtrees of any node does not exceed 1. According to the requirements of the title, use the recursive method to continuously find the middle position in the given sequence and construct the search binary tree node. Please refer to the code for details.

Three, problem-solving code

class Solution {
public:
    //最小高度树满足的条件:任意节点的左右子树的高度差不能超过1
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return dfs(nums, 0, nums.size()-1);
    }

    TreeNode* dfs(vector<int>& nums, int l, int r)
    {
        if(l > r)
            return NULL;
        int mid = (l+r) >> 1;
        TreeNode* node = new TreeNode(nums[mid]);
        node->left = dfs(nums, l, mid-1);
        node->right = dfs(nums, mid+1, r);
        return node;  
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108143614