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
|
716 Discussions
|
Please Login in order to post a comment
include
include
include
include
include
using namespace std; vector leftNode, rightNode; int swapLevel;
void traverse(int node=1){ if (node == -1) return; traverse(leftNode[node]); cout << node << " "; traverse(rightNode[node]); if (node == 1) cout << endl; }
void swap(int level=1, int node=1) { if (node == -1) return; if (level % swapLevel == 0) { int tmp = leftNode[node]; leftNode[node] = rightNode[node]; rightNode[node] = tmp; } swap(level+1, leftNode[node]); swap(level+1, rightNode[node]); }
int main() { int count;
cin>>count; leftNode.push_back(0); rightNode.push_back(0); while(count--){ int L, R; cin>>L>>R; leftNode.push_back(L); rightNode.push_back(R); } cin>>count; while(count--){ cin >> swapLevel; swap(); traverse(); } return 0; }
SOLUTION
include
include
struct node { int id; int depth; struct node *left, *right; };
void inorder(struct node* tree) { if(tree == NULL) return;
}
int main(void) { int no_of_nodes, i = 0; int l,r, max_depth,k; struct node* temp = NULL; scanf("%d",&no_of_nodes); struct node* tree = (struct node *) calloc(no_of_nodes , sizeof(struct node)); tree[0].depth = 1; while(i < no_of_nodes ) { tree[i].id = i+1; scanf("%d %d",&l,&r); if(l == -1) tree[i].left = NULL; else { tree[i].left = &tree[l-1]; tree[i].left->depth = tree[i].depth + 1; max_depth = tree[i].left->depth; }
}
SOLUTION
include
include
struct node { int id; int depth; struct node *left, *right; };
void inorder(struct node* tree) { if(tree == NULL) return;
}
int main(void) { int no_of_nodes, i = 0; int l,r, max_depth,k; struct node* temp = NULL; scanf("%d",&no_of_nodes); struct node* tree = (struct node *) calloc(no_of_nodes , sizeof(struct node)); tree[0].depth = 1; while(i < no_of_nodes ) { tree[i].id = i+1; scanf("%d %d",&l,&r); if(l == -1) tree[i].left = NULL; else { tree[i].left = &tree[l-1]; tree[i].left->depth = tree[i].depth + 1; max_depth = tree[i].left->depth; }
}
Python 3 Version, it's mostly the same as g503420777's code but it's derived from trying to analyze as normal node traversal
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.