day23
思路:
中左右。
先判断中间结点是否符合条件。如果符合就继续原样搜索。
如果不符合,有三种情况。
1. 为空 ,直接返回空
2. 小于 low ,根据二叉树的特性,此时root的右子树,还是会可能存在符合条件的结点。(右子树比根结点的值要大。) 所以向此时的 root->right 去遍历,并将符合的结点返回。
3. 大于 high 。同理,根据二叉树的特性,此时的root的左子树,还是会可能存在符合条件的结点。所以向 root->left去遍历。
代码如下:
class Solution {
public:
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;
}
};