mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0450.删除二叉搜索树中的节点.md
添加0450删除二叉搜索树中的节点 C# 版本
This commit is contained in:
@ -769,6 +769,38 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### C#
|
||||||
|
|
||||||
|
> 递归法:
|
||||||
|
```C#
|
||||||
|
public TreeNode DeleteNode(TreeNode root, int key) {
|
||||||
|
// 第一种情况:没找到删除的节点,遍历到空节点直接返回了
|
||||||
|
if (root == null) return null;
|
||||||
|
if(key == root.val) {
|
||||||
|
//第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
|
||||||
|
if(root.left == null && root.right == null) return null;
|
||||||
|
//第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
|
||||||
|
if (root.left == null && root.right != null) return root.right;
|
||||||
|
//第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
|
||||||
|
if (root.left != null && root.right == null) return root.left;
|
||||||
|
//第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
|
||||||
|
// 并返回删除节点右孩子为新的根节点。
|
||||||
|
if(root.left != null && root.right != null) {
|
||||||
|
TreeNode leftNode = root.right; // 找右子树最左面的节点
|
||||||
|
while(leftNode.left != null)
|
||||||
|
leftNode = leftNode.left;
|
||||||
|
leftNode.left = root.left; // 把要删除的节点(root)左子树放在leftNode的左孩子的位置
|
||||||
|
return root.right; // 返回旧root的右孩子作为新root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(root.val > key) root.left = DeleteNode(root.left, key);
|
||||||
|
if(root.val < key) root.right = DeleteNode(root.right, key);
|
||||||
|
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user