力扣labuladong——一刷day70

2023-12-13 03:50:48

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言


这道题的难点在于要一直剪枝,直到没有值为 0 的叶子节点为止,只有从后序遍历位置自底向上处理才能获得最高的效率

一、力扣814. 二叉树剪枝

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
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){
            if(root.val == 0){
                return null;
            }
        }
        return root;
    }
}

二、力扣1325. 删除给定值的叶子节点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode removeLeafNodes(TreeNode root, int target) {
        if(root == null){
            return null;
        }
        TreeNode left = removeLeafNodes(root.left,target);
        TreeNode right = removeLeafNodes(root.right,target);
        if(left == null && right == null){
            if(root.val == target){
                return null;
            }
        }
        root.left = left;
        root.right = right;
        return root;
    }
}

文章来源:https://blog.csdn.net/ResNet156/article/details/134918378
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。