Skip to content

Commit 95df4f2

Browse files
Merge pull request youngyangyang04#585 from Spongecaptain/patch-5
Update 0669.修剪二叉搜索树.md
2 parents da4c890 + 64b4a59 commit 95df4f2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

problems/0669.修剪二叉搜索树.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,7 @@ Go:
296296
* Right *TreeNode
297297
* }
298298
*/
299+
// 递归
299300
func trimBST(root *TreeNode, low int, high int) *TreeNode {
300301
if root==nil{
301302
return nil
@@ -312,6 +313,37 @@ func trimBST(root *TreeNode, low int, high int) *TreeNode {
312313
root.Right=trimBST(root.Right,low,high)
313314
return root
314315
}
316+
// 迭代
317+
func trimBST(root *TreeNode, low int, high int) *TreeNode {
318+
if root == nil {
319+
return nil
320+
}
321+
// 处理 root,让 root 移动到[low, high] 范围内,注意是左闭右闭
322+
for root != nil && (root.Val<low||root.Val>high){
323+
if root.Val < low{
324+
root = root.Right
325+
}else{
326+
root = root.Left
327+
}
328+
}
329+
cur := root
330+
// 此时 root 已经在[low, high] 范围内,处理左孩子元素小于 low 的情况(左节点是一定小于 root.Val,因此天然小于 high)
331+
for cur != nil{
332+
for cur.Left!=nil && cur.Left.Val < low{
333+
cur.Left = cur.Left.Right
334+
}
335+
cur = cur.Left
336+
}
337+
cur = root
338+
// 此时 root 已经在[low, high] 范围内,处理右孩子大于 high 的情况
339+
for cur != nil{
340+
for cur.Right!=nil && cur.Right.Val > high{
341+
cur.Right = cur.Right.Left
342+
}
343+
cur = cur.Right
344+
}
345+
return root
346+
}
315347
```
316348

317349

0 commit comments

Comments
 (0)