-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelete Node in a BST.cs
More file actions
40 lines (36 loc) · 1.04 KB
/
Delete Node in a BST.cs
File metadata and controls
40 lines (36 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode DeleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (root.val > key) {
root.left = DeleteNode(root.left, key);
} else if (root.val < key) {
root.right = DeleteNode(root.right, key);
} else {
root = DeleteNode(root);
}
return root;
}
private TreeNode DeleteNode(TreeNode root) {
if (root.left != null && root.right != null) {
var temp = root.right;
while (temp.left != null) {
temp = temp.left;
}
root.val = temp.val;
root.right = DeleteNode(root.right, root.val);
return root;
}
return root.left != null ? root.left : root.right;
}
}