Binary Tree Pruning


  • 0

    Click here to see the full article post


  • 1
    M

    Less convoluted:

        public TreeNode pruneTree(TreeNode root) {
            if ( root == null ) return null;
            
            root.left = pruneTree (root.left);
            root.right = pruneTree (root.right);
            
            if ( root.val == 0 && root.left == null && root.right == null ) return null;
            
            return root;
        }

  • 0
    A

    @mrincodi did a great job simplifying this. I've added comments in my javascript version:

    var pruneTree = function(root) {
      if (!root) return null
    
      // recurse as deep as you can until you hit a leaf
      root.left = pruneTree(root.left)
      root.right = pruneTree(root.right)
      
      // we only keep leaf nodes if they contain a 1
      const isLeaf = !root.left && !root.right
      if (isLeaf && root.val !== 1) return null
      
      return root
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.