mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
46 lines
1.1 KiB
C#
46 lines
1.1 KiB
C#
|
/**
|
||
|
* 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 DeleteNode(TreeNode root, int key) {
|
||
|
if (root == null) {
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
if (key == root.val) {
|
||
|
if (root.left == null) {
|
||
|
return root.right;
|
||
|
}
|
||
|
|
||
|
if (root.right == null) {
|
||
|
return root.left;
|
||
|
}
|
||
|
|
||
|
// find successor
|
||
|
var node = root.right;
|
||
|
while (node.left != null) {
|
||
|
node = node.left;
|
||
|
}
|
||
|
|
||
|
root.val = node.val;
|
||
|
root.right = DeleteNode(root.right, node.val);
|
||
|
} else if (key < root.val) {
|
||
|
root.left = DeleteNode(root.left, key);
|
||
|
} else if (key > root.val) {
|
||
|
root.right = DeleteNode(root.right, key);
|
||
|
}
|
||
|
|
||
|
return root;
|
||
|
}
|
||
|
}
|