814. Binary Tree Pruning

T: O(n)
S: O(n)
/**
 * 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) {
        int result = dfs(root);
        if (result == 0) {
            return null;
        }
        return root;
    }
    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int leftCount = dfs(node.left);
        if (leftCount == 0) {
            node.left = null;
        }
        int rightCount = dfs(node.right);
        if (rightCount == 0) {
            node.right = null;
        }

        return node.val == 1 ? 1 : 0 + leftCount + rightCount;
    }
}

/**
T: O(n)
S: O(n)

 */

Last updated