Binary search tree: pruning the binary search tree

Binary search tree: build a binary search tree

Insert picture description here
The first reaction is reconstruction. It seems that other people's answers have found that it is not as complicated as reconstruction.

 TreeNode* trimBST(TreeNode* root, int low, int high) {
    
    
        if(root == nullptr)
        return root;

        if(root->val < low)
        {
    
    
            TreeNode *right = trimBST(root->right, low, high);//root的左子树值都小于root,因此将右子树中符合区间条件的节点返回给上一层
            return right;
        }
        if(root->val > high)
        {
    
    
            TreeNode *left = trimBST(root->left, low, high);//同理
            return left;
        }
        //下一层处理完左子树的结果赋给root->left,处理完右子树的结果赋给root->right。
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
    }

To simplify:

TreeNode* trimBST(TreeNode* root, int low, int high) {
    
    
        if (root == nullptr) 
        return nullptr;
        if (root->val < low) 
        return trimBST(root->right, low, high); 
        if (root->val > high) 
        return trimBST(root->left, low, high); 
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
    }

Guess you like

Origin blog.csdn.net/cckluv/article/details/113091884