-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0450-Delete-node-in-a-BST.cs
More file actions
38 lines (32 loc) · 1020 Bytes
/
0450-Delete-node-in-a-BST.cs
File metadata and controls
38 lines (32 loc) · 1020 Bytes
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
using Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0450.Delete_node_in_a_BST
{
public class _0450_Delete_node_in_a_BST
{
public TreeNode DeleteNode(TreeNode root, int key)
{
if (root == null) return root;
if (key < root.val)
root.left = DeleteNode(root.left, key);
else if (key > root.val)
root.right = DeleteNode(root.right, key);
else // root.val == key
{
if (root.left == null)
return root.right;
if (root.right == null)
return root.left;
// root.left & root.right != null
TreeNode node = root.right;
while (node.left != null)
node = node.left;
root.val = node.val;
root.right = DeleteNode(root.right, node.val);
}
return root;
}
}
}