zoukankan      html  css  js  c++  java
  • 每日一题力扣669 修剪二叉搜索树

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

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

    示例 1:


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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/trim-a-binary-search-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution:
        def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
            def test(root):
                if not root:
                    return None
                if root.val >high:#如果中间的节点比最大值还要大,那么右节点肯定也是更大了,
                    return test(root.left)
                if root.val<low:
                    return test(root.right)
                else:
                    root.left=test(root.left)#否则,该点的左子树,就是test函数作用在其左子树上的结果
                    root.right=test(root.right)
                    return root
            
            return test(root)
  • 相关阅读:
    Python进阶08 生成器
    Python进阶07 迭代
    Python进阶06 列表推导
    Python进阶05 函数property
    Python基础14 集合
    支付宝支付和微信消息推送
    Redis
    django之contenttype
    数据分析系列
    IPython
  • 原文地址:https://www.cnblogs.com/liuxiangyan/p/14677813.html
Copyright © 2011-2022 走看看