首页 > 其他分享 >LeetCode_669_修剪二叉搜索树

LeetCode_669_修剪二叉搜索树

时间:2022-11-01 11:02:54浏览次数:60  
标签:right TreeNode 669 val 二叉 trimBST root LeetCode left


题目描述:

给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。

示例 1:

输入:
1
/ \
0 2

L = 1
R = 2

输出:
1
\
2
示例 2:

输入:
3
/ \
0 4
\
2
/
1

L = 1
R = 3

输出:
3
/
2
/
1

思路:trimBST()返回的就是结果二叉树
如果root->val>R,说明结果二叉树应该在左子树上
如果root->val<L,说明结果二叉树应该在右子树上
其他情况,就进行左右子树都剪枝

/**
* 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 root;
//根和左子树都减掉
if(root->val<L)
return trimBST(root->right,L,R);
//根和右子树都减掉
if(root->val>R)
return trimBST(root->left,L,R);
//正常范围内的剪枝
root->left=trimBST(root->left,L,R);
root->right=trimBST(root->right,L,R);
return root;
}
};

LeetCode_669_修剪二叉搜索树_二叉搜索树


标签:right,TreeNode,669,val,二叉,trimBST,root,LeetCode,left
From: https://blog.51cto.com/u_15855860/5812309

相关文章

  • Leetcode第1662题:检查两个字符串数组是否相等(Check if two string arrays are equival
    解题思路输入是两个字符串数组,包含的元素数目不一定相同,每个元素包含的字符数目也不一定相同。使用两个指针p和i分别记录遍历的元素位置和字符位置。指针p1和p2分别表示......
  • 数据结构 玩转数据结构 5-2 测试自己的Leetcode链表代码
    0课程地址https://coding.imooc.com/lesson/207.html#mid=13434 1重点关注1.1leetCode的代码 如何本地调试详见3.1 1.2遗忘的......
  • [LeetCode] 1293. Shortest Path in a Grid with Obstacles Elimination
    Youaregivenan mxn integermatrix grid whereeachcelliseither 0 (empty)or 1 (obstacle).Youcanmoveup,down,left,orrightfromandtoanem......
  • LeetCode刷题记录.Day2
    移除元素题目链接 27.移除元素-力扣(LeetCode)classSolution{public:intremoveElement(vector<int>&nums,intval){intslotIndex=0;......
  • [Leetcode Weekly Contest]317
    链接:LeetCode[Leetcode]2455.可被三整除的偶数的平均值给你一个由正整数组成的整数数组nums,返回其中可被3整除的所有偶数的平均值。注意:n个元素的平均值等于n个......
  • Leetcode第481题:神奇字符串(Magical string)
    解题思路根据题意,我们可以把ss看成是由「11组」和「22组」交替组成的,重点在于每组内的数字是一个还是两个,这可以从ss自身上知道。构造到ss的长度达到nn时停止......
  • leetcode-191-easy
    NumberOf1BitsWriteafunctionthattakesanunsignedintegerandreturnsthenumberof'1'bitsithas(alsoknownastheHammingweight).Note:Notetha......
  • leetcode-278-easy
    FirstBadVersionYouareaproductmanagerandcurrentlyleadingateamtodevelopanewproduct.Unfortunately,thelatestversionofyourproductfailsthe......
  • leetcode-268-easy
    MissingNumberGivenanarraynumscontainingndistinctnumbersintherange[0,n],returntheonlynumberintherangethatismissingfromthearray.Exam......
  • leetcode-500-easy
    KeyboardRowGivenanarrayofstringswords,returnthewordsthatcanbetypedusinglettersofthealphabetononlyonerowofAmericankeyboardliketheim......