We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This problem description needs a bit of work - I do appreciate the examples and their clarity as I was able to deduce the actual index recording rules from them. That said, the provided instructions for recording the index values of a tree were wrong.
This is not correct (doesn't match their provided solutions). This implies we record the first node visited, which will always be the left or right child of the root node. This also implies that if a node has a left and right child, we record the value of the node only after exploring both the left and right sub-trees. The examples make it clear that this is not the case.
The actual logic for printing values seems to be: "record an index whenever arriving at a node and its left subtree is fully explored (true if there is no left sub-tree)". Note that this handles leaf nodes since they have no left subtree.
i.e. the traversal logic to get the indices in the order they want is: traverse tree in an in-order, depth first way. Record the index for a node when arriving at that node AND that node's left subtree has been fully explored - happens when:
- arriving at a node and it has no left sub-tree
- arriving at a node from its left sub-tree
I spent most of my time on this problem figuring that part out, which was frustrating
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Swap Nodes [Algo]
You are viewing a single comment's thread. Return to all comments →
This problem description needs a bit of work - I do appreciate the examples and their clarity as I was able to deduce the actual index recording rules from them. That said, the provided instructions for recording the index values of a tree were wrong.
From the instructions:
This is not correct (doesn't match their provided solutions). This implies we record the first node visited, which will always be the left or right child of the root node. This also implies that if a node has a left and right child, we record the value of the node only after exploring both the left and right sub-trees. The examples make it clear that this is not the case.
The actual logic for printing values seems to be: "record an index whenever arriving at a node and its left subtree is fully explored (true if there is no left sub-tree)". Note that this handles leaf nodes since they have no left subtree.
i.e. the traversal logic to get the indices in the order they want is: traverse tree in an in-order, depth first way. Record the index for a node when arriving at that node AND that node's left subtree has been fully explored - happens when: - arriving at a node and it has no left sub-tree - arriving at a node from its left sub-tree
I spent most of my time on this problem figuring that part out, which was frustrating