Skip to content

Commit 7de5392

Browse files
committed
create: 0701-insert-into-a-binary-search-tree.ts
1 parent 914ca1f commit 7de5392

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
15+
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
16+
if (!root) {
17+
return new TreeNode(val);
18+
}
19+
20+
if (val > root.val) {
21+
root.right = insertIntoBST(root.right, val);
22+
}
23+
if (val < root.val) {
24+
root.left = insertIntoBST(root.left, val);
25+
}
26+
27+
return root;
28+
}

0 commit comments

Comments
 (0)