814 Binary Tree Pruning

1. Question

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.)

Example 1:
Input:
 1
  \ 
   0 
  / \
 0   1

Output: 

 1
  \
   0
    \
     1

Explanation:

Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.

2. Implementation

(1) DFS

思路: post order traversal, 先处理左子树和右子树,然后如果当前node是leaf且它的值为0的话,把该node删除

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

3. Time & Space Complexity

DFS: 时间复杂度O(n), 空间复杂度: O(h)

Last updated

Was this helpful?