# 701.Insert Into a Binary Search Tree

**701.Insert Into a Binary Search Tree**

难度:Medium

> Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example,

Given the tree:

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

And the value to insert: 5 You can return this binary search tree:

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

This tree is also valid:

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

First, we need to locate the position to insert, then insert it.\
Show codes:

```
/**
 * 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) {
        TreeNode* cur=root;
         TreeNode* newNode = new TreeNode(val);
         while(true)
         {
             if(cur->val > val )
             {
                 if(cur->left )
                     cur=cur->left;
                 else
                 {
                     cur->left=newNode;
                     break;
                 }
             }
             else
             {
                 if(cur->right)
                 cur=cur->right;
                 else
                 {
                     cur->right=newNode;
                     break;
                 }
             }
         }
         return root;
    }
};
```

> 执行用时 :88 ms, 在所有 C++ 提交中击败了99.16%的用户\
> 内存消耗 :32.8 MB, 在所有 C++ 提交中击败了87.32%的用户


---

# 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://dfine.gitbook.io/leetcode/701.insert_into_a_binary_search_tree.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.
