> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/04-10-2022-701.-insert-into-a-binary-search-tree.md).

# 04/10/2022 701. Insert into a Binary Search Tree

701\. Insert into a Binary Search Tree

Method: recursion

check the val with the root val. If it is greater than than the root val, we recursively call the function with root.right and val. Otherwise we call with root.left and val. If we the root is null, then we can create a new TreeNode with the val.

Time O(H)

Space O(H)

```
// Some code
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        
        if (root.val > val) root.left = insertIntoBST(root.left, val);
        if (root.val < val) root.right = insertIntoBST(root.right, val);
        
        return root;
        
    }
}
```
