1325.cpp (996B)
1 class Solution { 2 public: 3 TreeNode *removeLeafNodes(TreeNode *root, int target) { 4 TreeNode dummy(-1, root, nullptr); 5 unordered_map<TreeNode *, TreeNode *> um = {{root, &dummy}}; 6 stack<TreeNode *> st({root}); 7 while (!st.empty()) { 8 TreeNode *root = st.top(); 9 if (root->val < 0) { 10 st.pop(); 11 root->val = -root->val; 12 if (!root->left && !root->right && root->val == target) { 13 TreeNode *parent = um[root]; 14 (parent->left == root ? parent->left : parent->right) = nullptr; 15 } 16 continue; 17 } 18 root->val = -root->val; 19 if (root->left) { 20 um[root->left] = root; 21 st.push(root->left); 22 } 23 if (root->right) { 24 um[root->right] = root; 25 st.push(root->right); 26 } 27 } 28 return dummy.left; 29 } 30 };