Skip to content

Commit 51c2487

Browse files
authored
Create 0701-insert-into-a-binary-search-tree.js
1 parent f5488aa commit 51c2487

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* h = height of the tree, could be n.
11+
* Time O(h) | Space O(h)
12+
* @param {TreeNode} root
13+
* @param {number} val
14+
* @return {TreeNode}
15+
*/
16+
var insertIntoBST = function(root, val) {
17+
18+
const dfs = (root) => {
19+
if(!root) {
20+
return new TreeNode(val);
21+
}
22+
if(val > root.val) {
23+
root.right = dfs(root.right);
24+
} else {
25+
root.left = dfs(root.left);
26+
}
27+
return root;
28+
}
29+
30+
return dfs(root);
31+
};

0 commit comments

Comments
 (0)