From d52cb2aa4901be727d077c2aaf3aafd9ed0519ee Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Tue, 7 Sep 2021 21:47:41 +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 | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 35c8e24d..6b8ab7ed 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -278,6 +278,33 @@ 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; + } + } + if (root.val > key) root.left = deleteNode(root.left, key); + if (root.val < key) root.right = deleteNode(root.right, key); + return root; + } +``` ## Python