|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
| 5 | +/** |
| 6 | + * 814. Binary Tree Pruning |
| 7 | + * |
| 8 | + * We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1. |
| 9 | + * Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. |
| 10 | + * (Recall that the subtree of a node X is X, plus every node that is a descendant of X.) |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * Input: [1,null,0,0,1] |
| 14 | + * Output: [1,null,0,null,1] |
| 15 | + * Explanation: |
| 16 | + * Only the red nodes satisfy the property "every subtree not containing a 1". |
| 17 | + * The diagram on the right represents the answer. |
| 18 | + * 1 1 |
| 19 | + * \ \ |
| 20 | + * 0 ----> 0 |
| 21 | + * / \ \ |
| 22 | + * 0 1 1 |
| 23 | + * |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * Input: [1,0,1,0,0,0,1] |
| 27 | + * Output: [1,null,1,null,1] |
| 28 | + * 1 1 |
| 29 | + * / \ \ |
| 30 | + * 0 1 ----> 1 |
| 31 | + * / \ / \ \ |
| 32 | + * 0 0 0 1 1 |
| 33 | + * |
| 34 | + * |
| 35 | + * Example 3: |
| 36 | + * Input: [1,1,0,1,1,0,1,0] |
| 37 | + * Output: [1,1,0,1,1,null,1] |
| 38 | + * 1 1 |
| 39 | + * / \ / \ |
| 40 | + * 1 0 -----> 1 0 |
| 41 | + * / \ / \ / \ \ |
| 42 | + * 1 1 0 1 1 1 1 |
| 43 | + * / |
| 44 | + * 0 |
| 45 | + * |
| 46 | + * |
| 47 | + * Note: |
| 48 | + * |
| 49 | + * The binary tree will have at most 100 nodes. |
| 50 | + * The value of each node will only be 0 or 1.*/ |
| 51 | +public class _814 { |
| 52 | + public static class Solution1 { |
| 53 | + /**credit: https://leetcode.com/problems/binary-tree-pruning/discuss/122730/C%2B%2BJavaPython-Self-Explaining-Solution-and-2-lines*/ |
| 54 | + public TreeNode pruneTree(TreeNode root) { |
| 55 | + if (root == null) { |
| 56 | + return root; |
| 57 | + } |
| 58 | + root.left = pruneTree(root.left); |
| 59 | + root.right = pruneTree(root.right); |
| 60 | + if (root.left == null && root.right == null && root.val == 0) { |
| 61 | + return null; |
| 62 | + } |
| 63 | + return root; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments