《中英双解》leetCode Convert Sorted Array to Binary Search Tree(将有序数组转换为二叉搜索树)

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树

Example 1:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in a strictly increasing order.

一些生词:

ascending order
英 [əˈsendɪŋ ˈɔːdə(r)]   美 [əˈsendɪŋ ˈɔːrdər]  
递升次序

subtrees:子树

这一题首先要想到的是用递归来解决问题,看原题可以知道,我们需要重复的进行添加元素,下面来看看代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
       return buildTree(nums,0,nums.length - 1);
   }
    public TreeNode buildTree(int[] nums,int low,int high){
      int mid = low + ((high - low) >> 1);
      TreeNode treeNode = new TreeNode(nums[mid]);
      treeNode.left = buildTree(nums,low,mid-1);
      treeNode.right = buildTree(nums,mid+1,high);
      return treeNode;
   }
}

我是怎么想到用递归的呢》其实,我一开始也想不出来用递归这个方法,因为我遇到了一个问题,就是找到了数组的中间元素,我面临的是这个中间元素作为根节点,需要一直创建新的节点,加到他的左子树和右子树中,而且根据题目也可以看出,数组mid左边的元素需要全部加到左子树中,数组mid右边的元素需要一直加到右子树中,一开始我想用for循环进行加入,但是面临的问题是你只能在一个节点重复的进行赋值,达不到一直增加新节点的效果。此时,我就想,该怎么解决这个办法呢,这个时候就想到了递归。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值