I'm a programming student, are there any "strategies" to tackling Binary
Tree problems?
I hope this is an acceptable question. I understand the mode of thinking
for recursion where I want to think of base case(s) then recursive cases
but with some of the more difficult BST problems I just draw blanks and it
feels like I get lost without having a good direction.
With LinkedLists for example, it seems there's a pattern to approach a
problem but BTs seem like either you know it or don't. Any tips/pointers?
The only concept I've seem to have gotten down is that if I'm dealing with
null nodes and I want to do something with them or about them, I'll have
it as a case
if(root == null)
//do something
or if I don't have anything to do with the null nodes then I use the
inverted base case
if(root != null)
//do stuff
else
//do nothing for null case
But even then I will come to a loss at what next. I guess here's an
example of a problem I'm stuck with and don't know how to approach. I'm
not necessarily looking for an answer, just a potential strategy to deal
with questions like this (and regular binary tree questions).
Write a method numberNodes that changes the data stored in a binary tree,
assigning sequential integers starting with 1 to each node so that a
pre-order traversal will produce the numbers in order(1, 2, 3, etc.). For
example, given the tree referenced by tree below at left, the call of
tree.numberNodes(); would overwrite the existing data assigning the nodes
values from 1 to 6 so that a pre-order traversal of the tree would produce
1, 2, 3, 4, 5, 6.
[ascii picture goes here but i wasn't able to format it properly when
copying]
You are not to change the structure of the tree. You are simply changing
the values stored in the data fields. Your method should return a count of
how many nodes were in the tree.
Assume that you are adding this method to the IntTree class as defined below:
public class IntTree { private IntTreeNode overallRoot; ... }
After staring at the code some more I figure I should be using my int
count as a means to determine if I travel to the left root or right root
since it's a binary search tree but I'm still unable to implement this
functionality... ahh coding block!
No comments:
Post a Comment