File tree 1 file changed +66
-0
lines changed
1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /****************************************
2
+ 701. Insert into a Binary Search Tree
3
+
4
+ Difficulty: Medium
5
+
6
+ Given the root node of a binary search tree (BST) and a value to be inserted into the tree,
7
+ insert the value into the BST.
8
+ Return the root node of the BST after the insertion.
9
+ It is guaranteed that the new value does not exist in the original BST.
10
+
11
+ Note that there may exist multiple valid ways for the insertion,
12
+ as long as the tree remains a BST after insertion.
13
+ You can return any of them.
14
+
15
+ For example,
16
+ Given the tree:
17
+ 4
18
+ / \
19
+ 2 7
20
+ / \
21
+ 1 3
22
+ And the value to insert: 5
23
+ You can return this binary search tree:
24
+ 4
25
+ / \
26
+ 2 7
27
+ / \ /
28
+ 1 3 5
29
+
30
+ This tree is also valid:
31
+ 5
32
+ / \
33
+ 2 7
34
+ / \
35
+ 1 3
36
+ \
37
+ 4
38
+ ****************************************/
39
+
40
+
41
+ /**
42
+ * Definition for a binary tree node.
43
+ * public class TreeNode {
44
+ * int val;
45
+ * TreeNode left;
46
+ * TreeNode right;
47
+ * TreeNode(int x) { val = x; }
48
+ * }
49
+ */
50
+ class Solution {
51
+ public TreeNode insertIntoBST(TreeNode root, int val) {
52
+ if (root == null) {
53
+ return new TreeNode(val);
54
+ }
55
+
56
+ if (val < root.val) {
57
+ root.left = insertIntoBST(root.left, val);
58
+ }
59
+ else {
60
+ root.right = insertIntoBST(root.right, val);
61
+ }
62
+
63
+ return root;
64
+ }
65
+ }
66
+
You can’t perform that action at this time.
0 commit comments