关于修剪二叉搜索树中的递归思路
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==nullptr){
return root;
}
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;
}
};
这里在面对不符合条件的节点时,采取的方式是跳过当前节点然后处理后面的节点。然后底下面对符合条件的节点也要对它的左子树和右子树进行遍历
浙公网安备 33010602011771号