[leetcode]814. Binary Tree Pruning
Analysis
周四不知道快不快乐—— [有点想回家过暑假的冲动!]
We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. (Recall that the subtree of a node X is X, plus every node that is a descendant of X.) 删除一棵树中所有不含1的子树,递归解决,要注意的是判断某节点要不要删除要在处理完其左右子树之后(i.e. example 2)~
Implement
/**
* 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:
TreeNode* pruneTree(TreeNode* root) {
if(!root)
return NULL;
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
if(!root->left && !root->right && root->val ==
0)
return NULL;
return root;
}
};