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
|
727 Discussions
|
Please Login in order to post a comment
Python code:
sys.setrecursionlimit(2000)
def swapNodes(indexes, queries):
def swap(indexes, depth, idx, k, res):
C# solution using a Dictionary and Depth-First Search:
The below solution passes all eleven test cases, all of which execute in at most one second.
The use of a Dictionary < int, int[] > object to keep track of the node indices helps ensure that the algorithm will skip any node child with a value of -1 (i.e. no child), since the key values stored have a value of at least 1 by default. The value corresponding to each key is an integer array containing the depth of the node at index 0 and the indices of its children (if any) at indices 1 and 2. The DFS traversal algorithm checks if the depth is divisible by the current query value, and if such is the case, the values at indices 1 and 2 are switched before the DFS recurs. Using a dictionary and checking if the key is contained in the node list means we won't have to worry about exceptions due to accessing indices outside of the range of the tree.
Boring explanation, easy problem.
Solution steps:
1) create a binary tree with given indexes
2) traverse it to set depths of each node (and store all nodes of depth d in a dictionary D)
3) for each query q, iterate through D[q], D[2q], ..., until D stops containing the key, and swap the children of all nodes of each node list
4) perform in-order traversal, as expected
The explanation for this problem is incredible hard, it complicates things without a reason, and the examples are confusing. It needs a lot of rewritting.
I don't understand why the output is how it is:
(Using C++)