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

# 701. Insert into a Binary Search Tree

## 1.問題

* 插入新元素到BST

![](/files/-LKMDW6AJEOfdOPfbsLa)

## 2.想法

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        insert(root, new TreeNode(val));
        return root;
    }
private:
    TreeNode* insert(TreeNode* root, TreeNode* node) {
        if (root == NULL) {
            return node;
        }
        
        if (node->val <= root->val) {
            root->left = insert(root->left, node);
        } else {
            root->right = insert(root->right, node);
        }
        
        return root;
    }
};
```

## 4.Performance

![](/files/-LKME51d10WBy99VPPil)
