Skip to content

Commit

Permalink
Merge pull request neetcode-gh#3000 from dkiryanov/csharp/0701-insert…
Browse files Browse the repository at this point in the history
…-into-a-binary-search-tree

Added a C# solution to 701. Insert into a Binary Search Tree
  • Loading branch information
MHamiid authored Sep 28, 2023
2 parents 2b8eaa1 + fa47c47 commit 249b37d
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions csharp/0701-insert-into-a-binary-search-tree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{
public TreeNode InsertIntoBST(TreeNode root, int val)
{
if (root is null) return new TreeNode(val);

TreeNode cur = root;

while (cur is not null)
{
if (cur.val < val)
{
if (cur.right is null)
{
cur.right = new TreeNode(val);
break;
}

cur = cur.right;
continue;
}

if (cur.val > val)
{
if (cur.left is null)
{
cur.left = new TreeNode(val);
break;
}

cur = cur.left;
continue;
}
}

return root;
}
}

0 comments on commit 249b37d

Please sign in to comment.