From 64b4a590729606a9466465a2e20f3685f9ac5d85 Mon Sep 17 00:00:00 2001 From: wjjiang <48505670+Spongecaptain@users.noreply.github.com> Date: Tue, 10 Aug 2021 10:17:59 +0800 Subject: [PATCH] =?UTF-8?q?Update=200669.=E4=BF=AE=E5=89=AA=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 Go 语言迭代版本 --- problems/0669.修剪二叉搜索树.md | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 26394eaa..c13af226 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -296,6 +296,7 @@ Go: * Right *TreeNode * } */ +// 递归 func trimBST(root *TreeNode, low int, high int) *TreeNode { if root==nil{ return nil @@ -312,6 +313,37 @@ func trimBST(root *TreeNode, low int, high int) *TreeNode { root.Right=trimBST(root.Right,low,high) return root } +// 迭代 +func trimBST(root *TreeNode, low int, high int) *TreeNode { + if root == nil { + return nil + } + // 处理 root,让 root 移动到[low, high] 范围内,注意是左闭右闭 + for root != nil && (root.Valhigh){ + if root.Val < low{ + root = root.Right + }else{ + root = root.Left + } + } + cur := root + // 此时 root 已经在[low, high] 范围内,处理左孩子元素小于 low 的情况(左节点是一定小于 root.Val,因此天然小于 high) + for cur != nil{ + for cur.Left!=nil && cur.Left.Val < low{ + cur.Left = cur.Left.Right + } + cur = cur.Left + } + cur = root + // 此时 root 已经在[low, high] 范围内,处理右孩子大于 high 的情况 + for cur != nil{ + for cur.Right!=nil && cur.Right.Val > high{ + cur.Right = cur.Right.Left + } + cur = cur.Right + } + return root +} ```