首页 > 其他分享 >leetcode 669. Trim a Binary Search Tree

leetcode 669. Trim a Binary Search Tree

时间:2023-05-30 18:05:24浏览次数:33  
标签:Trim Binary Search right TreeNode val dummy root left

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.

Example 1:

Input: 
    1
   / \
  0   2

  L = 1
  R = 2

Output: 
    1
      \
       2

Example 2:

Input: 
    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output: 
      3
     / 
   2   
  /
 1

  解法1:

凡是树的题目无非DFS,BFS,递归或者迭代做,仅此而已。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def trimBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: TreeNode
        """
        # use DFS, root first then left and right
        # if L <= root.val <= R: 
        #    new_root with root.val; 
        #    new_root.left = self.trimBST(root.left, L, root.val)
        #    new_root.right = self.trimBST(root.right, root.val, R)
        #    return new_root
        # elif root.val < L:
        #    return self.trimBST(root.right, L, R)
        # elif root.val > R:
        #    return self.trimBST(root.left, L, R)
        
        if root is None:
            return None
        if L <= root.val <= R:
            new_root = TreeNode(root.val)
            new_root.left = self.trimBST(root.left, L, root.val)
            new_root.right = self.trimBST(root.right, root.val, R)
            return new_root
        elif root.val < L:
            return self.trimBST(root.right, L, R)
        elif root.val > R:
            return self.trimBST(root.left, L, R)

迭代解法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null) {
            return root;
        }
        while (root.val < L || root.val > R) {
            if (root.val < L) {
                root = root.right;
            }
            if (root.val > R) {
                root = root.left;
            }
        }
        TreeNode dummy = root;
        while (dummy != null) {
            while (dummy.left != null && dummy.left.val < L) {
                dummy.left = dummy.left.right;
            }
            dummy = dummy.left;
        }
        dummy = root;
        while (dummy != null) {
            while (dummy.right != null && dummy.right.val > R) {
                dummy.right = dummy.right.left;
            }
            dummy = dummy.right;
        }
        return root;
    }
}

 

标签:Trim,Binary,Search,right,TreeNode,val,dummy,root,left
From: https://blog.51cto.com/u_11908275/6381143

相关文章

  • leetcode 617. Merge Two Binary Trees
    Giventwobinarytreesandimaginethatwhenyouputoneofthemtocovertheother,somenodesofthetwotreesareoverlappedwhiletheothersarenot.Youneedtomergethemintoanewbinarytree.Themergeruleisthatiftwonodesoverlap,thensumn......
  • leetcode 257. Binary Tree Paths
    Givenabinarytree,returnallroot-to-leafpaths.Forexample,giventhefollowingbinarytree: 1/\23\5Allroot-to-leafpathsare:["1->2->5","1->3"]#Definitionforabinarytreenode.#classTreeNode(obje......
  • leetcode 671. Second Minimum Node In a Binary Tree
    Givenanon-emptyspecialbinarytreeconsistingofnodeswiththenon-negativevalue,whereeachnodeinthistreehasexactlytwoorzerosub-node.Ifthenodehastwosub-nodes,thenthisnode'svalueisthesmallervalueamongitstwosub-nodes.G......
  • leetcode 107. Binary Tree Level Order Traversal II
    Givenabinarytree,returnthebottom-uplevelordertraversalofitsnodes'values.(ie,fromlefttoright,levelbylevelfromleaftoroot).Forexample:Givenbinarytree[3,9,20,null,null,15,7],3/\920/\157returnits......
  • Elasticsearch专题精讲——API规范—— 基于 URL 的访问控制
    API规范——基于URL的访问控制https://www.elastic.co/guide/en/elasticsearch/reference/8.8/api-conventions.html#api-url-access-control Elasticsearch中的multi-search(多搜索)、multi-get(多获取)和bulk(批量请求)是在一个请求中执行多个操作的方法。如果使用基于URL......
  • 芯片trim
    1,芯片trim原理12,芯片trim原理23,集成电路Trimming4,有关芯片trim之polyfuse和metalfuse问题......
  • Elasticsearch专题精讲——API规范—— 一般表达式
    API规范——一般表达式1、格式化搜索结果 当任何请求URL加pretty=true参数时,返回的JSON都是格式化的(仅用于调试)。另一个选项是设置format=yaml,结果以更可读的yaml格式返回。2、可读输出 统计数据以适合人(例如"exists_time":"1h"或"size":"1KB")和计算机(例如......
  • Elasticsearch专题精讲——API规范——多索引
    API规范——多索引ElasticsearchRESTAPI使用HTTP协议,采用JOSN格式。 大多数API都支持跨多个索引执行,可以使用简单的test1,test2,test3表示法(或对所有索引执行,用_all)。它还支持通配符,例如test*或te*t或*test,以及排除(-),例如-test3. 所有多索引API都支持以......
  • 某种程度上亚马逊 OpenSearch 成功了
    导读据悉,某种程度上亚马逊OpenSearch成功了某种程度上亚马逊OpenSearch成功了2021年,开发Elasticsearch和Kibana的Elastic公司宣布更改许可证,此举旨在禁止云服务商如AWS使用它的软件作为一种服务提供给客户,但这也意味着这两个软件不再是开源软件。发生此事......
  • can't not find Node.js binary ''path",make sure Node.js is installed and in your
    vscode中node执行debug报错报错信息如下 思路1:检查node是否安装成功win+R输入cmd  能够正常显示版本号,则证明没有问题,接着换个思路 思路2:根据提示打开图示的'launch.json'文件,在页面补充 runtimeExecutable具体补充什么内容呢?在overflow中找到了nginx中需要补......