/** * 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; } };
这里在面对不符合条件的节点时,采取的方式是跳过当前节点然后处理后面的节点。然后底下面对符合条件的节点也要对它的左子树和右子树进行遍历
标签:修剪,right,TreeNode,val,树中,二叉,high,root,left From: https://www.cnblogs.com/yanzhao-x/p/16970746.html