814. 二叉树剪枝
给你二叉树的根结点 root ,此外树的每个结点的值要么是 0 ,要么是 1 。
返回移除了所有不包含 1 的子树的原二叉树。
节点 node 的子树为 node 本身加上所有 node 的后代。
示例 1:
输入:root = [1,null,0,0,1]
输出:[1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
示例 2:
输入:root = [1,0,1,0,0,0,1] 输出:[1,null,1,null,1] 示例 3:
输入:root = [1,1,0,1,1,0,1,0] 输出:[1,1,0,1,1,null,1]
分析
闲来无事,刷个题,对于递归问题,我的思路一般就是先看深度为2的怎么处理,化繁为简。搭好框架,在递归。
这个题如果是子节点,且节点是值是0,那就可以剪掉。
代码
class Solution {
public TreeNode pruneTree(TreeNode root) {
if (root == null) return null;
// 注意下面这两行的顺序,一定要先递归到子节点,再处理。
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (root.val==0){
if (root.left==null && root.right==null){
return null;
}
}
return root;
}
}
最后
好无聊啊!