给定二叉树根结点 root
,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
示例1: 输入: [1,null,0,0,1] 输出: [1,null,0,null,1] 解释: 只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
示例2: 输入: [1,0,1,0,0,0,1] 输出: [1,null,1,null,1]
示例3: 输入: [1,1,0,1,1,0,1,0] 输出: [1,1,0,1,1,null,1]
说明:
- 给定的二叉树最多有
100
个节点。 - 每个节点的值只会为
0
或1
。
- 这题比较讲究呢,虽然做法也是递归,但前序遍历递归和后序遍历递归还是差距很大的,就拿这题来说把,我故意在AC的情况下,把后序改为前序来递归,果然WA了,收获很大~~
- 通过前序后序的对比,可以发现前序只能删除叶子节点为0的,但非叶子为0并且左右节点为0的情况却不行,但后序就不一样了,后序先把叶子节点通过return null删除后,上面所说的情况也成为了叶子节点,以此递归~~
- 希望有所收获~~
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root==null)
return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.left==null && root.right==null && root.val==0)
return null;
return root;
}
}
WA的前序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root==null)
return null;
if(root.left==null && root.right==null && root.val==0)
return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
return root;
}
}
这代码可读性真的差,不过嘛,也参考下吧,网上beat代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 这个肯定能做……
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root == null){
return null;
}
return digui(root);
}
public TreeNode digui(TreeNode root){
if(root != null){
if(root.val == 0 && root.left == null && root.right == null){
return null;
}else if(root.val == 1 && root.left == null && root.right == null){
return root;
}
TreeNode leftInfo = digui(root.left);
TreeNode rightInfo = digui(root.right);
if(leftInfo == null){
root.left = null;
}
if(rightInfo == null){
root.right = null;
}
if(root.val == 0 && root.left == null && root.right ==null){
return null;
}else{
return root;
}
}else{
return null;
}
}
}