convert-sorted-array-to-binary-search-tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        int n=num.length;
        if(num==null||n==0){
            return null;
        }
        return createBst(num,0,n-1);
    }
    public static TreeNode createBst(int num[],int start,int end){
        if(start>end){
            return null;
        }        int mid=(start+end+1)/2;
        TreeNode root=new TreeNode(num[mid]);
        
        root.left=createBst(num,start,mid-1);
        root.right=createBst(num,mid+1,end);
        return root;
    }
}

使用递归的方法,求中间节点时注意是start+end+1;注意边界条件。

猜你喜欢

转载自blog.csdn.net/qq_30035749/article/details/90761369
今日推荐