← Home

1325. Delete Leaves With a Given Value

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
132

Let's make this one less mysterious. For 1325. Delete Leaves With a Given Value, the solution in this repository is mainly a two pointers solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are removeLeafNodes.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 32 ms, faster than 13.93% of C++ online submissions for Delete Leaves With a Given Value.
02//Memory Usage: 27 MB, less than 100.00% of C++ online submissions for Delete Leaves With a Given Value.
03
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13class Solution {
14public:
15    TreeNode* removeLeafNodes(TreeNode* root, int target) {
16        stack<TreeNode*> stk;
17        bool changed = false;
18        //bool: whether the child is left
19        map<TreeNode*, pair<bool, TreeNode*>> parent;
20        TreeNode* cur;
21        
22        do{
23            parent.clear();
24            changed = false;
25            
26            stk.push(root);
27            parent[root] = make_pair(false, nullptr);
28
29            while(!stk.empty()){
30                cur = stk.top(); stk.pop();
31
32                //post-order
33                if(cur->right){
34                    stk.push(cur->right);
35                    parent[cur->right] = make_pair(false, cur);
36                }
37                if(cur->left){
38                    stk.push(cur->left);
39                    parent[cur->left] = make_pair(true, cur);
40                }
41
42                if(!cur->left && !cur->right && cur->val == target){
43                    if(parent[cur].second == nullptr){
44                        //cur node is root
45                        return nullptr;
46                    }
47                    //cur node is not root
48                    if(parent[cur].first){
49                        parent[cur].second->left = nullptr;
50                    }else{
51                        parent[cur].second->right = nullptr;
52                    }
53                    changed = true;
54                }
55
56            }
57            
58        }while(changed);
59        
60        return root;
61    }
62};
63
64//Recursion Solution
65//https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/484264/JavaC%2B%2BPython-Recursion-Solution
66//Runtime: 20 ms, faster than 85.19% of C++ online submissions for Delete Leaves With a Given Value.
67//Memory Usage: 20.5 MB, less than 100.00% of C++ online submissions for Delete Leaves With a Given Value.
68/**
69 * Definition for a binary tree node.
70 * struct TreeNode {
71 *     int val;
72 *     TreeNode *left;
73 *     TreeNode *right;
74 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
75 * };
76 */
77class Solution {
78public:
79    TreeNode* removeLeafNodes(TreeNode* root, int target) {
80        if(root->left) root->left = removeLeafNodes(root->left, target);
81        if(root->right) root->right = removeLeafNodes(root->right, target);
82        //root->left can only be same as root->right when they are both nullptr
83        return (root->left == root->right) && (root->val == target) ? nullptr : root;
84    }
85};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.