题解 | #将升序数组转化为平衡二叉搜索树#

将升序数组转化为平衡二叉搜索树

https://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d?tpId=117&tqId=37720&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D117&difficulty=undefined&judgeStatus=undefined&tags=&title=

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
  public:
    /**
     * 
     * @param num int整型vector 
     * @return TreeNode类
     */
    TreeNode* sortedArrayToBST(vector<int>& num) {
      //  平衡二叉树的中序遍历就是递增数组
      if (num.empty()) {
        return nullptr;
      }
      
      return curision(num, 0, num.size() - 1);
    }
  private:
  //  递归、分治最后归并
    TreeNode* curision(std::vector<int> &num, int left, int right) {
      if (left > right) {
        return nullptr;
      }
      
      int mid = left + (right - left) / 2;
      
      TreeNode *l = curision(num, left,  mid - 1);
      TreeNode *r = curision(num, mid + 1, right);
      
      TreeNode *root = new TreeNode(num[mid]);
      root->left = l;
      root->right = r;
      
      return root;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务