LeetCode 669 Trim a Binary Search Tree 解题报告

题目要求

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

题目分析及思路

题目给出一棵二叉搜索树和一个上下界,要求对树剪枝,使得结果树中的所有结点的值都在给定的区间内。二叉搜索树的定义为:该树可为空;不空的话,若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值,若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值。根据该定义,我们可以使用递归的方法,当root的值位于LR之间,则递归修剪其左右子树,返回root。当root的值小于L,则其左子树的值都小于L,抛弃左子树,返回修剪过的右子树。当root的值大于R,则其右子树的值都大于R,抛弃右子树,返回修剪过的左子树。

python代码

# Definition for a binary tree node.

# class TreeNode:

#     def __init__(self, x):

#         self.val = x

#         self.left = None

#         self.right = None

class Solution:

    def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:

        if not root:

            return

        if root.val < L:

            return self.trimBST(root.right, L, R)

        elif root.val > R:

            return self.trimBST(root.left, L, R)

        else:

            root.left = self.trimBST(root.left, L, R)

            root.right = self.trimBST(root.right, L, R)

            return root

        

        

        

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10429289.html