/**
* 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 nullptr;
}
root->left=removeLeafNodes(root->left,target);//先删除左边
root->right=removeLeafNodes(root->right,target);//再删除右边
if(!root->left&&!root->right&&root->val==target)//在回溯的时候删除
{
return nullptr;//如果某一个节点是叶子节点而且还是值等于target的,那么直接删除
}
return root;
}
};
Leetcode:1325. 删除给定值的叶子节点
最新推荐文章于 2022-07-19 10:23:54 发布