I was asked this in an interview a few years ago. I choked on it. Completely froze and gave a very wrong answer. The interviewers didn't push me on it. They just kinda nodded their heads and moved on with slightly confused looks on their faces. I left really annoyed with myself and worked out the right answer to the question about 17 minutes after I'd left the place. The sad thing is that it was such an easy question. All I had to do was draw a tree and work out the solution. Instead I didn't bother thinking at all about how we use and traverse trees. I was so nervous that I spewed out some nonsense.
The answer I came up with in the car afterwards, and I think this is a correct answer is this:
You have to first decide on the method tree traversal: depth- or breadth-first. Say we choose breadth-first. Next we traverse the tree and store each node in the database table. Say the table has 4 columns: an auto-increment index, node_name, node_value, and parent_node. So each row in our table contains (index, node_name, node_value, parent_node)
Now we traverse the tree, first visiting the root node and storing it. Assume it's named p0. So we store (index, p0, p0-value, null). We then visit the root node's children from left to right and for each of these we store (index+1, pn, pn-value, p0) where index+1 is the auto-increment index, pn is the node name, pn-value is the node value, and p0 is the parent node (currently root). Repeat until the we have breadth-first traversed and stored the entire tree.
To reconstruct the tree, select the root node from the database (parent_node = null) and add it to the tree. Then select all nodes in the database with the root node as parent, in order of their index, and add them to the tree as children of root. Next select all nodes in the database with a parent equal to the left-most child of the root node, and add them to the tree in order of their indices. We have to breadth-first traverse the tree as we add nodes to it to complete it.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment