Featured image of post 669. 修剪二叉搜索树

669. 修剪二叉搜索树

题目描述

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

所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

示例 1:

  • 输入:root = [1,0,2], low = 1, high = 2
  • 输出:[1,null,2]

示例 2:

  • 输入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
  • 输出:[3,2,null,1]

提示:

  • 树中节点数在范围 [1, 104] 内
  • 0 <= Node.val <= 104
  • 树中每个节点的值都是 唯一
  • 题目数据保证输入是一棵有效的二叉搜索树
  • 0 <= low <= high <= 104

解法一:递归

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * 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 {
        return trimBST(root.Right, low, high)
    } else if root.Val > high {
        return trimBST(root.Left, low, high)
    } else if root.Val == low {
        root.Left = nil
        root.Right = trimBST(root.Right, low + 1, high)
        return root
    } else if root.Val == high {
        root.Right = nil
        root.Left = trimBST(root.Left, low, high - 1)
        return root
    } else {
        root.Left = trimBST(root.Left, low, root.Val - 1)
        root.Right = trimBST(root.Right, root.Val + 1, high)
        return root
    }
}

官方题解如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func trimBST(root *TreeNode, low, high int) *TreeNode {
    if root == nil {
        return nil
    }
    if root.Val < low {
        return trimBST(root.Right, low, high)
    }
    if root.Val > high {
        return trimBST(root.Left, low, high)
    }
    root.Left = trimBST(root.Left, low, high)
    root.Right = trimBST(root.Right, low, high)
    return root
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/05/06 22:55:42
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计