mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #585 from Spongecaptain/patch-5
Update 0669.修剪二叉搜索树.md
This commit is contained in:
@ -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.Val<low||root.Val>high){
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user