leetcode_108_Convert Sorted Array to Binary Search Tree

描述:

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

思路:

思路就是按二分查找的思路进行中序建树,递归建树。

代码:

public TreeNode sortedArrayToBST(int[] num) {
		if(num.length==0||num==null)
			return null;
        TreeNode rootNode =new TreeNode(0);
        int start=0,end=num.length-1;
        createTree(rootNode, num, start, end); 
        return rootNode;
    }
	public void createTree(TreeNode root,int []num, int start,int end)
	{
		if(start>end)
		{
			root=null;
			return;
		}
		int mid=(start+end)/2;
		if(start<=mid-1)
		{
			root.left=new TreeNode(0);
			createTree(root.left, num, start, mid-1);
		}
		root.val=num[mid];
		if(mid+1<=end)
		{
			root.right=new TreeNode(0);
			createTree(root.right, num, mid+1, end);
		}
		
	}

结果:


你可能感兴趣的:(array,递归,sorted,convert,中序)