leetcode

    xiaoxiao2021-03-25  203

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST 给有序数组,创建 平衡二叉搜索树

    网友解法:

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { // 网友方法 public TreeNode sortedArrayToBST(int[] num) { if (num.length == 0) { return null; } TreeNode head = helper(num, 0, num.length - 1); return head; } public TreeNode helper(int[] num, int low, int high) { if (low > high) { // Done return null; } int mid = (low + high) / 2; TreeNode node = new TreeNode(num[mid]); node.left = helper(num, low, mid - 1); node.right = helper(num, mid + 1, high); return node; } }
    转载请注明原文地址: https://ju.6miu.com/read-1179.html

    最新回复(0)