Skip to content

Commit fa47c47

Browse files
committed
Added a C# solution to 701. Insert into a Binary Search Tree
1 parent 2ae20b0 commit fa47c47

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public int val;
5+
* public TreeNode left;
6+
* public TreeNode right;
7+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
8+
* this.val = val;
9+
* this.left = left;
10+
* this.right = right;
11+
* }
12+
* }
13+
*/
14+
public class Solution
15+
{
16+
public TreeNode InsertIntoBST(TreeNode root, int val)
17+
{
18+
if (root is null) return new TreeNode(val);
19+
20+
TreeNode cur = root;
21+
22+
while (cur is not null)
23+
{
24+
if (cur.val < val)
25+
{
26+
if (cur.right is null)
27+
{
28+
cur.right = new TreeNode(val);
29+
break;
30+
}
31+
32+
cur = cur.right;
33+
continue;
34+
}
35+
36+
if (cur.val > val)
37+
{
38+
if (cur.left is null)
39+
{
40+
cur.left = new TreeNode(val);
41+
break;
42+
}
43+
44+
cur = cur.left;
45+
continue;
46+
}
47+
}
48+
49+
return root;
50+
}
51+
}

0 commit comments

Comments
 (0)