때때로 LeetCode 이진 검색 트리에 대한 질문 --Convert 정렬 된 배열을 브러시

이진 검색 트리에 정렬 된 배열로 변환

요소가 오름차순으로 정렬되어 배열 주어 높이 균형 BST로 변환.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0){
            return null;
        }
        TreeNode head=helper(nums,0,nums.length-1);
        return head;
    }
    public TreeNode helper(int[] nums,int low,int high){
        if(low>high){
            return null;
        }
        int mid=(high+low)/2;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=helper(nums,low,mid-1);
        root.right=helper(nums,mid+1,high);
        return root;
    }
}

분명히, 우리는 균형 이진 검색 트리를 얻기 위해, 우리는 배열에 중간 노드를 계속 복용해야하는 배열을 정렬해야합니다. 우리는 쉽게 배열이 2 개로 나누어 져있어 유지, 재귀 생각할 수, 배열의 중간 요소는 각각 왼쪽과 오른쪽 노드 노드, 그 대답에 할당됩니다.

게시 된 173 개 원래 기사 · 원 찬양 (110) ·은 10 만 + 조회수

추천

출처blog.csdn.net/qq_35564813/article/details/104736998