• 669. 修剪二叉搜索树


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

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

    示例 1:

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

    示例 2:

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

    提示:

    • 树中节点数在范围 [1, 104] 内
    • 0 <= Node.val <= 104
    • 树中每个节点的值都是 唯一 的
    • 题目数据保证输入是一棵有效的二叉搜索树
    • 0 <= low <= high <= 104
    1. class Solution {
    2. public:
    3. TreeNode* dfs(TreeNode* root,int low,int high){
    4. if(!root) return nullptr;
    5. if(root->val < low){
    6. //遍历到这个不合适的结点,不能停止,得继续看他的右子树
    7. TreeNode* left = dfs(root->right,low,high);
    8. return left;
    9. }
    10. if(root->val > high){
    11. //遍历到这个不合适的结点,不能停止,得继续看他的左子树
    12. TreeNode* right = dfs(root->left,low,high);
    13. return right;
    14. }
    15. //该节点符合,那就遍历左子树,右子树
    16. root->left = dfs(root->left,low,high);
    17. root->right = dfs(root->right,low,high);
    18. return root;
    19. }
    20. TreeNode* trimBST(TreeNode* root, int low, int high) {
    21. return dfs(root,low,high);
    22. }
    23. };

     

    1. class Solution {
    2. public:
    3. TreeNode* trimBST(TreeNode* root, int low, int high) {
    4. //迭代
    5. //让根节点在合适的位置。
    6. //让左子树的结点在区间
    7. //让右子树的节点在区间内
    8. while(root){
    9. if(root->val < low){
    10. root = root->right;
    11. }
    12. else if(root->val > high){
    13. root = root->left;
    14. }
    15. else break;
    16. }
    17. //root已经满足,处理左子树
    18. TreeNode* cur = root;
    19. while(cur){
    20. if(cur->left && cur->left->val < low){
    21. cur->left = cur->left->right;
    22. }
    23. //可以直接省略,else都是cur = cur->left;
    24. /*
    25. else if(cur->left && cur->left > high){
    26. cur = cur->left;
    27. }*/
    28. else cur = cur->left;
    29. }
    30. cur = root;
    31. while(cur){
    32. if(cur->right && cur->right->val > high){
    33. cur->right = cur->right->left;
    34. }
    35. //同理
    36. /*
    37. else if(cur->left && cur->left > high){
    38. cur = cur->left;
    39. }*/
    40. else cur = cur->right;
    41. }
    42. return root;
    43. }
    44. };

  • 相关阅读:
    字节跳动|后端|提前批|一面+二面+三面+HR 面
    【Matplotlib绘制图像大全】(十):Matplotlib使用boxplot()绘制箱线图
    应用决策树批量化自动生成【效果好】【非过拟合】的策略集
    嵌入式系统开发笔记88:认识51微控制器系统架构
    vue路由
    vue使用vue-video-player插件播放视频
    Mac 制作可引导安装器
    jupylab pandas按条件批量处理xls数据
    【小嘟陪你刷题02】牛客网——Java专项练习
    Android Anr traces.txt 最全最完整说明文档
  • 原文地址:https://blog.csdn.net/qq_63819197/article/details/133687908