Leetcode 5317: remove the given value of the leaf node

Title Description

Give you a binary tree with root as the root of an integer and a target, you remove all the leaf nodes of the target value.

Note that once you delete a target value of the leaf node, its parent may become a leaf node; if the value of the new leaf node also happens to target, then the node should be deleted.

In other words, you need to repeat this process can not continue until deleted.

 

Example 1:

Input: root = [1,2,3,2, null, 2,4], target = 2
Output: [1, null, 3, null, 4]
Explanation:
FIG top left, the green node is a leaf node, and the same value as their target (the same as 2), they will be deleted, to obtain an intermediate of FIG.
There is a new node into a leaf node and its value with the same target, it will be removed again to obtain a map of the far right.
Example 2:

Input: root = [1,3,3,3,2], target = 3
Output: [1,3, null, null, 2]
Example 3:

Input: root = [1,2, null, 2, null, 2], target = 2
Output: [1]
Explanation: each step of deleting a green leaf node (value of 2).
Example 4:

Input: root = [1,1,1], target = 1
Output: []
Example 5:

Input: root = [1,2,3], target = 1
Output: [1,2,3]
 

prompt:

1 <= target <= 1000
every tree up to 3000 nodes.
Each node value range is [1, 1000].

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/delete-leaves-with-a-given-value
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

 

Problem-solving ideas

class Solution {
public:
    void dfs(TreeNode* &root,int target){
        if(root == NULL) return;
        dfs(root->left,target);
        dfs(root->right,target);
        if(root->left==NULL && root->right==NULL && root->val==target) root = NULL;
    }
    TreeNode* removeLeafNodes(TreeNode* root, int target) {
        dfs(root,target);
        return root;
    }
};

 

Published 566 original articles · won praise 9 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_35338624/article/details/104042542