From 6a6d6f993aa496788325d1f4bb0d95c44ede202b Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Tue, 7 Sep 2021 21:48:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00450.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E8=8A=82=E7=82=B9.mdJava=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0450.删除二叉搜索树中的节点.md | 39 +++++++++---------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 6b8ab7ed..f11431e0 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -281,29 +281,28 @@ class Solution { ```java // 解法2 class Solution { - public TreeNode deleteNode(TreeNode root, int key) { - if (root == null) return root; - if (root.val == key) { - if (root.left == null) { - return root.right; - } - else if (root.right == null) { - return root.left; - } - else{ - TreeNode cur = root.right; - while (cur.left != null) { - cur = cur.left; - } - cur.left = root.left; - root = root.right; - return root; - } + public TreeNode deleteNode(TreeNode root, int key) { + if (root == null) return root; + if (root.val == key) { + if (root.left == null) { + return root.right; + } else if (root.right == null) { + return root.left; + } else { + TreeNode cur = root.right; + while (cur.left != null) { + cur = cur.left; } - if (root.val > key) root.left = deleteNode(root.left, key); - if (root.val < key) root.right = deleteNode(root.right, key); + cur.left = root.left; + root = root.right; return root; + } } + if (root.val > key) root.left = deleteNode(root.left, key); + if (root.val < key) root.right = deleteNode(root.right, key); + return root; + } +} ``` ## Python