0
点赞
收藏
分享

微信扫一扫

#108 Convert Sorted Array to Binary Search Tree

伊人幽梦 2022-04-13 阅读 40
java

Description

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

A 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.

Examples

Example 1:
在这里插入图片描述
在这里插入图片描述

Example 2:
在这里插入图片描述

Constraints:

思路

就是一个递归建立的过程,因为是排序完的,所以每次选取middle节点作为currNode就可以了,注意一下递归出口就没什么大问题

代码

/**
 * 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[] num) {
        if (num.length == 0) {
            return null;
        }
        TreeNode head = recursive(num, 0, num.length - 1);
        return head;
    }

    public TreeNode recursive(int[] num, int low, int high) {
        if (low > high)
            return null;
        int mid = (low + high) / 2;
        TreeNode node = new TreeNode(num[mid]);
        node.left = recursive(num, low, mid - 1);
        node.right = recursive(num, mid + 1, high);
        return node;
    }
}
举报

相关推荐

0 条评论