前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:669. Trim a Binary Search Tree

LeetCode笔记:669. Trim a Binary Search Tree

作者头像
Cloudox
发布2021-11-23 16:38:28
2580
发布2021-11-23 16:38:28
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题(Easy):

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:

Output:

Example 2: Input:

Output:

大意:

给出一个二叉查找树和最小、最大边界L和R,修剪树使其所有元素都在[L, R](R >= L)中。你可能需要改变树的根节点,所以结果应该返回裁剪后的树的新跟节点。 例1: 输入:

输出:

例2: 输入:

输出:

思路:

题目的意思就是让树只保留L到R范围内的数字,但是还是要保证树是个二叉查找树,虽然题目说了可能要改变根节点,但实际上只有根节点不在范围内的时候才需要更改。

思路就是递归遍历树的每个节点,将其看做根节点,判断是否为空、是否在范围内。如果不在,则要根据大小取左子节点或者右子节点作为新的根节点;如果在,则继续判断左右子节点。就直接用递归来做。

要注意每次递归都会在一开始就判断根节点是否为空,所以不用在递归前又去判断子节点是否为空,实测这将节省大量时间

代码:

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        if (root == NULL) return NULL;
        
        TreeNode *res = root;
        if (root->val > R) 
            res = trimBST(root->left, L, R);
        else if (root->val < L) 
            res = trimBST(root->right, L, R);
        else {
            res->left = trimBST(res->left, L, R);
            res->right = trimBST(res->right, L, R);
        }
        
        return res;
        
    }
};

他山之石:

除了用递归,也可以用循环来做,就循环判断左右子树,看大小是否在范围内,在则继续往下,否则将其左/右子节点作为当前循环的节点。

代码语言:javascript
复制
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        
       // find the proper root
        while(root->val<L || root->val>R)
        {
            if(root->val<L) { root = root->right; }
            else { root = root->left; }
        }
        
        // temporary pointer for left and right subtree
        TreeNode *Ltemp = root;
        TreeNode *Rtemp = root;
        
        // remove the elements larger than L
        while(Ltemp->left)
        {
            if( (Ltemp->left->val)<L ) { Ltemp->left = Ltemp->left->right; }
            else { Ltemp = Ltemp->left; }
        }
         // remove the elements larger than R
        while(Rtemp->right)
        {
            if( (Rtemp->right->val)>R) { Rtemp->right = Rtemp->right->left; }
            else { Rtemp = Rtemp->right; }
        }

        return root;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record


本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/1/2 下午,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题(Easy):
  • 大意:
  • 思路:
  • 代码:
  • 他山之石:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档