写麻烦了
flag
对于叶子节点表示val是0还是1
对于非叶子节点表示子节点删没删
dfs就好了
写了free就报错,不知道是我写的方式错了,还是oj有问题。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { void dfs(TreeNode* &root, int &flag) { if(root->val == 0) flag = 1; else flag = 0; if(root->left == nullptr && root->right == nullptr) { if(flag == 0) return; //free(r); root = nullptr; return; } if(root->left) dfs(root->left, flag); int flag1 = flag; if(root->right) dfs(root->right, flag); int flag2 = flag; if(flag1 == 1 && flag2 == 1 && root->val == 0) { TreeNode* r = root; //free(r); root = nullptr; } else { flag = 0; } return; } public: TreeNode* pruneTree(TreeNode* root) { int flag = -1; dfs(root, flag); return root; } };