-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1325.cpp
More file actions
30 lines (30 loc) · 996 Bytes
/
Copy path1325.cpp
File metadata and controls
30 lines (30 loc) · 996 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
TreeNode *removeLeafNodes(TreeNode *root, int target) {
TreeNode dummy(-1, root, nullptr);
unordered_map<TreeNode *, TreeNode *> um = {{root, &dummy}};
stack<TreeNode *> st({root});
while (!st.empty()) {
TreeNode *root = st.top();
if (root->val < 0) {
st.pop();
root->val = -root->val;
if (!root->left && !root->right && root->val == target) {
TreeNode *parent = um[root];
(parent->left == root ? parent->left : parent->right) = nullptr;
}
continue;
}
root->val = -root->val;
if (root->left) {
um[root->left] = root;
st.push(root->left);
}
if (root->right) {
um[root->right] = root;
st.push(root->right);
}
}
return dummy.left;
}
};