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.
- Prepare
- Data Structures
- Trees
- Swap Nodes [Algo]
- Discussions
Swap Nodes [Algo]
Swap Nodes [Algo]
Sort by
recency
|
712 Discussions
|
Please Login in order to post a comment
Here's my solution in C#, which passed all 11 test cases. For each node, you need to keep track of its index, children, and depth, the last one being important for the swap operation since you need to swap every node whose depth is a multiple of the number specified by each query.
Since the swaps affect nodes individually, you can perform the in-order traversal and the child swaps using the same recursion function.
Never have I ever seen a problem description as poorly written as this one. The fact that this statement has remained as it is for 9 years speak volumes.
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
No need to build a tree. Just swap the numbers in the list.
Java: