LeetCode 1325. 删除给定值的叶子节点(递归)

1. 题目

给你一棵以 root 为根的二叉树和一个整数 target ,请你删除所有值为 target 的 叶子节点

注意,一旦删除值为 target 的叶子节点,它的父节点就可能变成叶子节点;
如果新叶子节点的值恰好也是 target ,那么这个节点也应该被删除

也就是说,你需要重复此过程直到不能继续删除。
在这里插入图片描述

1 <= target <= 1000
每一棵树最多有 3000 个节点。
每一个节点值的范围是 [1, 1000]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-leaves-with-a-given-value
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

class Solution {
public:
    TreeNode* removeLeafNodes(TreeNode* root, int target) {
        if(!root)
            return NULL;
        TreeNode* l = removeLeafNodes(root->left, target);
        TreeNode* r = removeLeafNodes(root->right, target);
        if(!l)//左边节点可删,空也可以
            root->left = NULL;
        if(!r)//右边节点可删
            root->right = NULL;
        if(!l && !r && root->val == target)
            return NULL;//左右都没有,且val==target,可删,返回NULL
        else
            return root;
    }
};

52 ms 21.7 MB

  • 优化下
class Solution {
public:
    TreeNode* removeLeafNodes(TreeNode* root, int target) {
        if(!root)
            return NULL;
        root->left = removeLeafNodes(root->left, target);
        root->right = removeLeafNodes(root->right, target);
        if(!root->left && !root->right && root->val == target)
            return NULL;//左右都没有,且val==target,可删,返回NULL
        return root;
    }
};

32 ms

发布了852 篇原创文章 · 获赞 2303 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105546735