由于删除过程是只删除叶子节点,由于叶子节点删除后,非叶子节点可能会变为叶子节点,因此是一个后续遍历。
/**
* 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* removeLeafNodes(TreeNode* root, int target) {
if(root == nullptr) {
return root;
}
root->left = removeLeafNodes(root->left, target);
root->right = removeLeafNodes(root->right, target);
if(root->val == target && root->left == nullptr && root->right == nullptr) {
return nullptr;
}
return root;
}
};