JAVA:
public final TreeNode pruneTree(TreeNode root) { if(!hasOne(root)) return null; return root; } private final boolean hasOne(TreeNode node) { if (node == null) return false; boolean left = hasOne(node.left), right = hasOne(node.right); if (!left) node.left = null; if (!right) node.right = null; return left || right || node.val == 1; }
JS:
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var pruneTree = function (root) { if (!hasOne(root)) return null; return root; }; var hasOne = (node) => { if (!node) return false; let left = hasOne(node.left), right = hasOne(node.right); if (!left) node.left = null; if (!right) node.right = null; return left || right || node.val == 1; }