当前位置:网站首页>Leetcode problem solving -- 108 Convert an ordered array into a binary search tree

Leetcode problem solving -- 108 Convert an ordered array into a binary search tree

2022-07-06 03:07:00 Snowy solitary boat

public TreeNode sortedArrayToBST(int[] nums) {
    
    return sortedArrayToBST(nums,0,nums.length);
}

private TreeNode sortedArrayToBST(int[] nums,int low,int high){
    
    if (low>=high) return null;
    int middle = (low+high)>>1;
    TreeNode root = new TreeNode(nums[middle]);
    root.left = sortedArrayToBST(nums,low,middle);
    root.right = sortedArrayToBST(nums,middle+1,high);
    return root;
}

Ideas : Since we need to balance , So clearly , The middle node is balanced as the root node
Then further divide the intervals of the left and right subtrees , Recursive left and right subtrees , You can complete the topic

原网站

版权声明
本文为[Snowy solitary boat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132338038327.html