LeetCode题解之Binary Tree Pruning

1、题目描述

2、问题分析

使用递归

3、代码

 1 TreeNode* pruneTree(TreeNode* root) {
 2         if (root == NULL)
 3             return NULL;
 4         prun(root);
 5         return root;
 6     }
 7     
 8     void prun(TreeNode *root)
 9     {
10         if (root == NULL)
11             return;
12         if (!has_ones(root->left))
13             root->left = NULL;
14         
15         if (!has_ones(root->right))
16             root->right = NULL;
17         
18         prun(root->left);
19         prun(root->right);
20         
21         
22     }
23     
24     bool has_ones(TreeNode *t)
25     {
26         if (t == NULL)
27             return false;
28         return (t->val == 1) || has_ones(t->left) || has_ones(t->right);
29     }
原文地址:https://www.cnblogs.com/wangxiaoyong/p/10461303.html