LeetCode 669. 修剪二叉搜索树

题目链接:LeetCode 669. 修剪二叉搜索树

题意:

给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。

解题思路:

  • 由于这是一颗二叉搜索树,我们可以根据当前结点的值,或将当前结点及其右子树砍掉,或将当前结点及其左子树砍掉,或保留当前结点。
  • 所以可以使用递归,如果当前结点为空,则直接返回空。
  • 如果当前结点的值小于 L,则返回递归右子树的结果。
  • 如果当前结点的值大于 R,则返回递归左子树的结果。
  • 否则当前结点的左子树赋值为递归左子树的结果,右子树赋值为递归右子树的结果。

代码:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func trimBST(root *TreeNode, low int, high int) *TreeNode {

    if root == nil {
        return nil
    }
    if root.Val < low {
        right := trimBST(root.Right,low,high)
        return right
    }
    if root.Val > high{
        left := trimBST(root.Left,low,high)
        return left
    }
    root.Left = trimBST(root.Left,low,high)
    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
}
posted @ 2023-07-04 21:44  小星code  阅读(16)  评论(0)    收藏  举报