algorithm - Tips on solving binary tree/binary search tree problems using recursion (Java) -
i reviewing how solve binary trees/binary search tree problems in java using recursion , feel i'm struggling little bit. ex: manipulating/changing nodes in tree, counting patterns (# of ints, height of tree), etc. pretty use private helper methods.
i'd hear rules of thumb follow make life easier solve these problems. in advance!
edit: more specific.... i'm talking kinds of problems involving using recursion solve binary tree/bst problem. i'm not talking 1 problem. want know strategies solving these problems when creating methods solve them. things include or think of when solving them. can't more specific that. votes down.
first off, remember you're working on bst, not unsorted binary tree or non-binary general tree. means @ times can rely on bst invariant: every value in left subtree < < every value in right subtree. (equality included on 1 of sides in implementations). example relevant: in bst searching, if value you're trying find less this, there's no point looking in right subtree it; it's not there.
other that, treat recursion problem. means, given problem:
1) determine cases trivial , don't require recursion. write code correctly identifies these cases , returns trivial result. possibilities include height-0 tree, or no tree (null root).
2) other cases, determine of following make more sense: (both possible, 1 can cleaner)
- what non-recursive work reduce problem sub-problem , return solution (recursion @ end, potentially tail recursion)
- what recursive work need first in order solve problem. (recursion @ start, not tail recursion)
having private helper methods not bad thing; long serve distinct , useful function shouldn't feel bad writing them. there recursion problems cleaner , less redundant when split 3-4 methods rather cramming them one.
take bst problems , see if can identify general structure of solution before sit down code it. hope helps! may want have java tag on question if you're asking bst stuff java.
Comments
Post a Comment