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.

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
一开始没看懂题目,还以为L, R要自己确定,一想这样算下来可不是个easy级别啊,那LR怎么确定呢?

实在是不理解就瞄了一眼solution,才恍然大悟L,R是给定的值。

递归用起来真的很爽气。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        if(nullptr == root)
            return nullptr;
        if(root->val > R)
            return trimBST(root->left, L, R);
        if(root->val < L)
            return trimBST(root->right, L, R);
        root->left = trimBST(root->left, L, R);
        root->right = trimBST(root->right, L, R);
        return root;
    }
};

运行结果,看来效率没那么好的。

Runtime: 28 ms, faster than 14.71% of C++ online submissions for Trim a Binary Search Tree.

Memory Usage: 23.7 MB, less than 5.26% of C++ online submissions for Trim a Binary Search Tree.

找个高人的算法如下,

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        /*
        if(nullptr == root)
            return nullptr;
        if(root->val > R)
            return trimBST(root->left, L, R);
        if(root->val < L)
            return trimBST(root->right, L, R);
        root->left = trimBST(root->left, L, R);
        root->right = trimBST(root->right, L, R);
        return root;
        */
        if(!root)
            return nullptr;
        root->left=trimBST(root->left,L,R);
        root->right=trimBST(root->right,L,R);
        return root->val<L?root->right:root->val>R?root->left:root;
    }
};

看起来本质区别不大嘛,可是内存效率就好多了,其实两者各有千秋吧。

Runtime: 16 ms, faster than 95.51% of C++ online submissions for Trim a Binary Search Tree.

Memory Usage: 15 MB, less than 100.00% of C++ online submissions for Trim a Binary Search Tree.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值