class Solution {
public TreeNode pruneTree(TreeNode root) {
// 判断搜索的结果是什么,如果false就返回null,否则返回root
return search(root) ? root : null;
}
private boolean search(TreeNode root) {
if (root == null) {
return false;
}
// 后序遍历
boolean left = search(root.left);
boolean right = search(root.right);
if (left == false) {
root.left = null;
}
if (right == false) {
root.right = null;
}
return root.val == 1 || left || right;
}
}
原文:https://www.cnblogs.com/linzedian/p/14157753.html