|
1 | 1 | ## Algorithm
|
2 | 2 |
|
| 3 | +[701. Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) |
| 4 | + |
3 | 5 | ### Description
|
4 | 6 |
|
| 7 | +You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. |
| 8 | + |
| 9 | +Notice 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. |
| 10 | + |
| 11 | + |
| 12 | +Example 1: |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +``` |
| 17 | +Input: root = [4,2,7,1,3], val = 5 |
| 18 | +Output: [4,2,7,1,3,5] |
| 19 | +Explanation: Another accepted tree is: |
| 20 | +``` |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +Example 2: |
| 25 | + |
| 26 | +``` |
| 27 | +Input: root = [40,20,60,10,30,50,70], val = 25 |
| 28 | +Output: [40,20,60,10,30,50,70,null,null,25] |
| 29 | +``` |
| 30 | + |
| 31 | +Example 3: |
| 32 | + |
| 33 | +``` |
| 34 | +Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 |
| 35 | +Output: [4,2,7,1,3,5] |
| 36 | +``` |
| 37 | + |
| 38 | +Constraints: |
| 39 | + |
| 40 | +- The number of nodes in the tree will be in the range [0, 104]. |
| 41 | +- -108 <= Node.val <= 108 |
| 42 | +- All the values Node.val are unique. |
| 43 | +- -108 <= val <= 108 |
| 44 | +- It's guaranteed that val does not exist in the original BST. |
| 45 | + |
| 46 | + |
5 | 47 | ### Solution
|
6 | 48 |
|
7 |
| -```java |
| 49 | +```java |
| 50 | +/** |
| 51 | + * Definition for a binary tree node. |
| 52 | + * public class TreeNode { |
| 53 | + * int val; |
| 54 | + * TreeNode left; |
| 55 | + * TreeNode right; |
| 56 | + * TreeNode() {} |
| 57 | + * TreeNode(int val) { this.val = val; } |
| 58 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 59 | + * this.val = val; |
| 60 | + * this.left = left; |
| 61 | + * this.right = right; |
| 62 | + * } |
| 63 | + * } |
| 64 | + */ |
| 65 | +class Solution { |
| 66 | + public TreeNode insertIntoBST(TreeNode root, int val) { |
| 67 | + if (root == null){ |
| 68 | + return new TreeNode(val); |
| 69 | + } |
| 70 | + helper(root, val); |
| 71 | + return root; |
| 72 | + } |
8 | 73 |
|
| 74 | + public void helper(TreeNode root, int val){ |
| 75 | + if(root.left==null && val<root.val){ |
| 76 | + root.left = new TreeNode(val); |
| 77 | + return; |
| 78 | + } |
| 79 | + if(root.right==null && val>root.val){ |
| 80 | + root.right = new TreeNode(val); |
| 81 | + return; |
| 82 | + } |
| 83 | + if(val > root.val){ |
| 84 | + helper(root.right, val); |
| 85 | + }else{ |
| 86 | + helper(root.left, val); |
| 87 | + } |
| 88 | + } |
| 89 | +} |
9 | 90 | ```
|
10 | 91 |
|
11 | 92 | ### Discuss
|
|
0 commit comments