题目链接:力扣?
思路:递归
递归函数声明:
TreeNode* pruneTree(TreeNode* root) ;
操作左子树,操作右子树,最后加上根节点(二叉树的后序遍历)
需要把根节点的操作放在最后
/**
* 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:
TreeNode* pruneTree(TreeNode* root) {
if(root==NULL)
return NULL;
TreeNode *l=pruneTree(root->left);
TreeNode *r=pruneTree(root->right);
root->left=l;
root->right=r;
if(!root->left&&!root->right&&root->val==0)
{
return NULL;
}
return root;
}
};
|