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 null;

        pruneTree(root.left);
        pruneTree(root.right);
        if(root.left != null && root.left.val == 0 && isLeave(root.left))
            root.left = null;
        if(root.right != null && root.right.val == 0 && isLeave(root.right))
            root.right = null;

        return root;
    }

    public boolean isLeave(TreeNode n) {
        if(n == null)
            return false;

        return n.left == null && n.right == null;
    }
}

results matching ""

    No results matching ""