• 669. Trim a Binary Search Tree


    Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

    Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

    Example 1:

    Input: root = [1,0,2], low = 1, high = 2
    Output: [1,null,2]
    

    Example 2:

    Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
    Output: [3,2,null,1]

    题目:给二叉搜索树剪枝,使得所有节点值都在[low, high]之间

    思路:DFS。代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. TreeNode* trimBST(TreeNode* root, int low, int high) {
    15. if(!root) return NULL;
    16. while(root && (root->val < low || root->val > high)){
    17. if(root->val < low) root = root->right;
    18. else root = root->left;
    19. }
    20. if(!root) return NULL;
    21. root->left = trimBST(root->left, low, high);
    22. root->right = trimBST(root->right, low, high);
    23. return root;
    24. }
    25. };

  • 相关阅读:
    Halcon—3D测量算法的那点数学公式和代码实现
    GIS、GPS、RS综合应用
    FL Studio21.2破解版更新下载
    C 语言 void指针
    Java堆栈区别
    WPF列表样式
    AI大模型下的微服务会有什么?
    2050. 并行课程 III 拓扑排序
    严重内卷的电商直播还有机会吗?教你如何在电商直播中脱颖而出!
    电脑小技巧45个
  • 原文地址:https://blog.csdn.net/qing2019/article/details/126382314