llllmz

导航

669. 修剪二叉搜索树c

这题还是很难得。一看是想着当作普通二叉树所有节点都递归,但是很难做,难度很高。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* preorde(struct TreeNode* root,int low,int high){
    if(!root) return NULL;
    struct TreeNode* temp=root;
    if(root->val >= low && root->val <=high){
        root->left=preorde(root->left,low,high);
        root->right=preorde(root->right,low,high);
    }else{
        if(!root->left&&!root->right) return NULL;
        if(root->val>high){
            return preorde(root->left,low,high);
        }else if(root->val <low){
            return preorde(root->right,low, high);
        }
    }
    return root;
}

struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
    if(!root) return NULL;
    return preorde(root,low,high);
}

结果:

posted on 2024-03-07 14:43  神奇的萝卜丝  阅读(14)  评论(0)    收藏  举报