814. Binary Tree Pruning

We are given the head noderoot of a binary tree, where additionally every node's value is either a 0 or a 1.

Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

/**
 * 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 root;

        TreeNode leftResult = pruneTree(root.left);
        TreeNode rightResult = pruneTree(root.right);

        root.left = leftResult;
        root.right = rightResult;

        return (root.val == 0 && root.left == null && root.right == null) ? null : root;
    }


}

results for ""

    No results matching ""