【LeetCode】814. Binary Tree Pruning
一道树的剪枝,起初的想法是设一个函数,判断当前节点的子树是否含1,后来发现,后序遍历删除值为0的叶子节点就可以了。
代码如下:
/**
* 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==NULL)return NULL;
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
if(root->left==NULL&&root->right==NULL&&root->val==0)
{
return NULL;
}
return root;
}
};