forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#3000 from dkiryanov/csharp/0701-insert…
…-into-a-binary-search-tree Added a C# solution to 701. Insert into a Binary Search Tree
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |