1、题目链接
https://leetcode-cn.com/problems/binary-tree-pruning/
给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
2、分析
二叉树的大部分题目都可以使用递归来思考。
当前访问节点的左、右子树都为null(也就是为叶子节点),且当前节点的值为0,则需要删除。也就相当于删除值为0的叶子结点。
3、代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//若当前节点的左、右子树都为空或为0(叶子节点),且该节点值为0,则删
public TreeNode pruneTree(TreeNode root) {
if(root == null) return root;
return helper(root);
}
TreeNode helper(TreeNode root) {
if(root == null) return null;
TreeNode l = helper(root.left);
TreeNode r = helper(root.right);
if(l == null && r == null && root.val == 0) return null;
root.left = l;
root.right = r;
return root;
}
}