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.

I agree with you specially with the fact that it uses a lot of concepts from the other problems of trees section. I was able to achieve it using a simple algorithm:

Build the tree.

Repeat below steps for every value of k

Perform level order traversal (BFS) of the entire tree.

At each level, if level is a multiple of k then swap the
child of the nodes at that level.

After the level order traversal is done, perform in order traversal (DFS) to print the tree nodes data.

I used below definition of a node while building the tree:

class TreeNode
{
public int Data { get; set; }
public TreeNode LeftChild {get; set;}
public TreeNode RightChild { get; set; }
public int Depth { get; set; }
}

You don't need to build the tree at all. And you can swap and build the answer in one pass. Well, it might depend on the language and datastructure you're given.

## Swap Nodes [Algo]

You are viewing a single comment's thread. Return to all comments →

I agree with you specially with the fact that it uses a lot of concepts from the other problems of trees section. I was able to achieve it using a simple algorithm:

Repeat below steps for every value of k

child of the nodes at that level.

I used below definition of a node while building the tree:

My algorithm is the same as yours，but i did not pass all the test.

Yeah, same here. I only passed some tests. I wonder what we're doing wrong...

Thank you for this reply,

I spent like half an hour debugging with custom inputs only to find out I missed the part where you needed to swap at every depth multiple of k.

After that, my first algorithm was indeed correct :)

my algo is similar to yours but i am not able to clear 3 tests cases!

You don't need to build the tree at all. And you can swap and build the answer in one pass. Well, it might depend on the language and datastructure you're given.