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
|
708 Discussions
|
Please Login in order to post a comment
Java:
You actually dont need to create a class. Here's a way using just function:
Someone tell the auther he writes a shitty problem description.
There are 4 things that need to happen: 1. Build the tree (from the indexes 2D array), using a variation from BFS/level-order traversal (for loop) 2. Loop through the queries (
k
) to do the following: 2.1. Swap the nodes at the appropriate level 2.2. Traverse in-order in order to push the values into an array to be returned.The optimization is that steps 2.1 and 2.2 can be accomplished in a single iteration, resulting in O(n).
JavaScript