Code ideas
The first reaction should be to solve it recursively.
There are three conditions for the current node to be deleted:
- The current node value is 0
- Left subtree does not have 1
- The right subtree does not have 1
code
/**
* 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 {
public:
bool one(TreeNode *root){
if(!root) return false;
if(!one(root->left)) root->left = NULL; //左子树没有1,则删除左子树
if(!one(root->right)) root->right = NULL; //右子树没有1,则删除右子树
if(root->val) return true; //节点值为1,返回1
else{
if(!root->left && !root->right) return false; //节点值为0,且左右子树都被删除,则返回0
else return true; //有子树没被删除则返回1
}
}
TreeNode* pruneTree(TreeNode* root) {
if(!root) return root;
if(one(root)) return root;
else return NULL;
}
};