给定二叉树的根节点,树上每个节点的值是0或1。
返回这棵树,其中每个不包含1的子树已被删除。
(注意,节点X的子树是X,加上X的所有子孙节点。)
样例
样例 1:
输入: {1,#,0,0,1}
输出: {1,#,0,#,1}
解释: 只有红色节点满足属性“每个不包含1的子树”。下方的图代表了答案。
样例 2:
输入: {1,0,1,0,0,0,1}
输出: {1,#,1,#,1}
样例 3:
输入: {1,1,0,1,1,0,1,0}
输出: {1,1,0,1,1,#,1}
注意事项
- 每棵二叉树最多只有100个节点。
- 每个节点的值只会是
0
或1
.
输入测试数据 (每行一个参数)如何理解测试数据?
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root
* @return: the same tree where every subtree (of the given tree) not containing a 1 has been removed
*/
TreeNode * pruneTree(TreeNode * root)
{
// Write your code here
return bianli(root);
}
TreeNode* bianli(TreeNode* root)
{
if(root == NULL)
return NULL;
if(root->val == 1)
{
if(isequal(root->left) == false)
{
root->left = NULL;
}
else
{
root->left = bianli(root->left);
}
if(isequal(root->right) == false)
{
root->right = NULL;
}
else
{
root->right = bianli(root->right);
}
}
else if(root->val == 0)
{
if(isequal(root->left) == false)
{
root->left = NULL;
}
else
{
root->left = bianli(root->left);
}
if(isequal(root->right) == false)
{
root->right = NULL;
}
else
{
root->right = bianli(root->right);
}
if(root->left == NULL && root->right == NULL)
root = NULL;
}
return root;
}
bool isequal(TreeNode * root)
{
if(root == NULL)
return false;
if(root->val == 1)
return true;
return isequal(root->left) || isequal(root->right);
}
};