Skip to content

Commit c21dd0c

Browse files
committed
Add solution #701
1 parent 8ff9138 commit c21dd0c

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@
8989
648|[Replace Words](./0648-replace-words.js)|Medium|
9090
653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy|
9191
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
92+
701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium|
9293
713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium|
9394
722|[Remove Comments](./0722-remove-comments.js)|Medium|
9495
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 701. Insert into a Binary Search Tree
3+
* https://leetcode.com/problems/insert-into-a-binary-search-tree/
4+
* Difficulty: Medium
5+
*
6+
* You are given the root node of a binary search tree (BST) and a value
7+
* to insert into the tree. Return the root node of the BST after the
8+
* insertion. It is guaranteed that the new value does not exist in the
9+
* original BST.
10+
*
11+
* Notice that there may exist multiple valid ways for the insertion,
12+
* as long as the tree remains a BST after insertion. You can return
13+
* any of them.
14+
*/
15+
16+
/**
17+
* Definition for a binary tree node.
18+
* function TreeNode(val, left, right) {
19+
* this.val = (val===undefined ? 0 : val)
20+
* this.left = (left===undefined ? null : left)
21+
* this.right = (right===undefined ? null : right)
22+
* }
23+
*/
24+
/**
25+
* @param {TreeNode} root
26+
* @param {number} val
27+
* @return {TreeNode}
28+
*/
29+
var insertIntoBST = function(root, val) {
30+
if (!root) {
31+
return new TreeNode(val);
32+
}
33+
34+
if (val > root.val) {
35+
root.right = insertIntoBST(root.right, val);
36+
} else {
37+
root.left = insertIntoBST(root.left, val);
38+
}
39+
40+
return root;
41+
};

0 commit comments

Comments
 (0)