# 701. Insert into a Binary Search Tree

## 1.問題

* 插入新元素到BST

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKMCnmoOTS064JmeNpc%2F-LKMDW6AJEOfdOPfbsLa%2F20180820.jpg?alt=media\&token=78fcd28f-2d01-4cff-a696-d3784423aefc)

## 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKMCnmoOTS064JmeNpc%2F-LKME51d10WBy99VPPil%2F2018082002.jpg?alt=media\&token=91ffed6a-728b-4678-b558-1ba991d381eb)
