# 177.Convert Sorted Array to Binary Search Tree With Minimal Height

## 1.Description(Easy)

Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.

### Notice

There may exist multiple valid solutions, return any of them.

**Example**

Given`[1,2,3,4,5,6,7]`, return

```
     4
   /   \
  2     6
 / \    / \
1   3  5   7
```

## 2.Code

解决方法是选中点构造根节点，然后递归的构造左子树和右子树。

If we build BST from array, we can build it from top to bottom, like

1. choose the middle one as root,
2. build left sub BST via left part array
3. build right sub BST via right part array
4. do this recursively.

```
public TreeNode sortedArrayToBST(int[] A) {  
        return dfs(A,0,A.length-1);
    } 


    public TreeNode dfs(int[] A,int left,int right){
        if(left>right){
            return null;
        }
        int mid=(left+right)/2;
        TreeNode root=new TreeNode(A[mid]);
        root.left=dfs(A,left,mid-1);
        root.right=dfs(A,mid+1,right);
        return root;
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/2.binary-tree/177convert-sorted-array-to-binary-search-tree-with-minimal-height.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
