Skip to content

Commit

Permalink
create: 0701-insert-into-a-binary-search-tree.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
fahim041 committed Jun 19, 2023
1 parent 914ca1f commit 7de5392
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions typescript/0701-insert-into-a-binary-search-tree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/

function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
if (!root) {
return new TreeNode(val);
}

if (val > root.val) {
root.right = insertIntoBST(root.right, val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
}

return root;
}

0 comments on commit 7de5392

Please sign in to comment.