|
| 1 | +<h2>701. Insert into a Binary Search Tree</h2><h3>Medium</h3><hr><div><p>You are given the <code>root</code> node of a binary search tree (BST) and a <code>value</code> to insert into the tree. Return <em>the root node of the BST after the insertion</em>. It is <strong>guaranteed</strong> that the new value does not exist in the original BST.</p> |
| 2 | + |
| 3 | +<p><strong>Notice</strong> that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return <strong>any of them</strong>.</p> |
| 4 | + |
| 5 | +<p> </p> |
| 6 | +<p><strong>Example 1:</strong></p> |
| 7 | +<img alt="" src="https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg" style="width: 752px; height: 221px;"> |
| 8 | +<pre><strong>Input:</strong> root = [4,2,7,1,3], val = 5 |
| 9 | +<strong>Output:</strong> [4,2,7,1,3,5] |
| 10 | +<strong>Explanation:</strong> Another accepted tree is: |
| 11 | +<img alt="" src="https://assets.leetcode.com/uploads/2020/10/05/bst.jpg" style="width: 352px; height: 301px;"> |
| 12 | +</pre> |
| 13 | + |
| 14 | +<p><strong>Example 2:</strong></p> |
| 15 | + |
| 16 | +<pre><strong>Input:</strong> root = [40,20,60,10,30,50,70], val = 25 |
| 17 | +<strong>Output:</strong> [40,20,60,10,30,50,70,null,null,25] |
| 18 | +</pre> |
| 19 | + |
| 20 | +<p><strong>Example 3:</strong></p> |
| 21 | + |
| 22 | +<pre><strong>Input:</strong> root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 |
| 23 | +<strong>Output:</strong> [4,2,7,1,3,5] |
| 24 | +</pre> |
| 25 | + |
| 26 | +<p> </p> |
| 27 | +<p><strong>Constraints:</strong></p> |
| 28 | + |
| 29 | +<ul> |
| 30 | + <li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li> |
| 31 | + <li><code>-10<sup>8</sup> <= Node.val <= 10<sup>8</sup></code></li> |
| 32 | + <li>All the values <code>Node.val</code> are <strong>unique</strong>.</li> |
| 33 | + <li><code>-10<sup>8</sup> <= val <= 10<sup>8</sup></code></li> |
| 34 | + <li>It's <strong>guaranteed</strong> that <code>val</code> does not exist in the original BST.</li> |
| 35 | +</ul> |
| 36 | +</div> |
0 commit comments