From fa47c4769f96e6c5b3dc998d19b9716fd71ef5b8 Mon Sep 17 00:00:00 2001 From: "d.kiryanov" Date: Tue, 12 Sep 2023 09:29:26 +0300 Subject: [PATCH] Added a C# solution to 701. Insert into a Binary Search Tree --- .../0701-insert-into-a-binary-search-tree.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 csharp/0701-insert-into-a-binary-search-tree.cs diff --git a/csharp/0701-insert-into-a-binary-search-tree.cs b/csharp/0701-insert-into-a-binary-search-tree.cs new file mode 100644 index 000000000..d6294702e --- /dev/null +++ b/csharp/0701-insert-into-a-binary-search-tree.cs @@ -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; + } +} \ No newline at end of file