File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -769,6 +769,38 @@ impl Solution {
769769}
770770```
771771
772+ ### C#
773+
774+ > 递归法:
775+ ``` C#
776+ public TreeNode DeleteNode (TreeNode root , int key ) {
777+ // 第一种情况:没找到删除的节点,遍历到空节点直接返回了
778+ if (root == null ) return null ;
779+ if (key == root .val ) {
780+ // 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
781+ if (root .left == null && root .right == null ) return null ;
782+ // 第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
783+ if (root .left == null && root .right != null ) return root .right ;
784+ // 第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
785+ if (root .left != null && root .right == null ) return root .left ;
786+ // 第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
787+ // 并返回删除节点右孩子为新的根节点。
788+ if (root .left != null && root .right != null ) {
789+ TreeNode leftNode = root .right ; // 找右子树最左面的节点
790+ while (leftNode .left != null )
791+ leftNode = leftNode .left ;
792+ leftNode .left = root .left ; // 把要删除的节点(root)左子树放在leftNode的左孩子的位置
793+ return root .right ; // 返回旧root的右孩子作为新root
794+ }
795+ }
796+
797+ if (root .val > key ) root .left = DeleteNode (root .left , key );
798+ if (root .val < key ) root .right = DeleteNode (root .right , key );
799+
800+ return root ;
801+ }
802+ ```
803+
772804<p align =" center " >
773805<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
774806 <img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
You can’t perform that action at this time.
0 commit comments