给定二叉树根结点?root
?,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
输入: [1,null,0,0,1]
输出: [1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。
右图为返回的答案。
输入: [1,0,1,0,0,0,1]
输出: [1,null,1,null,1]
输入: [1,1,0,1,1,0,1,0]
输出: [1,1,0,1,1,null,1]
说明:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool validTree(TreeNode*& root){
if(root == NULL){
return true;
}else{
bool left = validTree(root->left);
bool right = validTree(root->right);
if(left == true){
root->left = NULL;
}
if(right == true){
root->right = NULL;
}
if(root->val == 1){
return false;
}else{
return left && right;
}
}
}
TreeNode* pruneTree(TreeNode* root) {
validTree(root);
return root;
}
};
原文:https://www.cnblogs.com/zhanzq/p/11075471.html