bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 814. Binary Tree Pruning

814. Binary Tree Pruning

Leetcode Solutions

Pruning a Binary Tree using Recursion

  1. Define a helper function containsOne(node) that returns True if the subtree rooted at node contains a 1, and False otherwise.
  2. If node is null, return False.
  3. Recursively call containsOne(node.left) and containsOne(node.right) to check the left and right subtrees.
  4. If the left subtree does not contain a 1, prune it by setting node.left to null.
  5. Similarly, if the right subtree does not contain a 1, prune it by setting node.right to null.
  6. Return True if the current node's value is 1 or if either the left or right subtree contains a 1.
  7. Call containsOne(root) from the main function pruneTree and return the potentially modified root.
UML Thumbnail

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...