LeetCode题解之Binary Tree Pruning

时间:2022-01-18 01:30:16

1、题目描述

LeetCode题解之Binary Tree Pruning

2、问题分析

使用递归

3、代码

 TreeNode* pruneTree(TreeNode* root) {
if (root == NULL)
return NULL;
prun(root);
return root;
} void prun(TreeNode *root)
{
if (root == NULL)
return;
if (!has_ones(root->left))
root->left = NULL; if (!has_ones(root->right))
root->right = NULL; prun(root->left);
prun(root->right); } bool has_ones(TreeNode *t)
{
if (t == NULL)
return false;
return (t->val == ) || has_ones(t->left) || has_ones(t->right);
}