Mirror of n-ary Tree - GeeksforGeeks
Given a Tree where every node contains variable number of children, convert the tree to its mirror.
http://www.geeksforgeeks.org/longest-path-undirected-tree/
Given an undirected tree, we need to find the longest path of this tree where a path is defined as a sequence of nodes.
This problem is same as diameter of n-ary tree.
Read full article from Mirror of n-ary Tree - GeeksforGeeks
Given a Tree where every node contains variable number of children, convert the tree to its mirror.
// Function to convert a tree to its mirrorvoid mirrorTree(Node * root){ // Base case: Nothing to do if root is NULL if (root==NULL) return; // Number of children of root int n = root->child.size(); // If number of child is less than 2 i.e. // 0 or 1 we do not need to do anything if (n < 2) return; // Calling mirror function for each child for (int i=0; i<n; i++) mirrorTree(root->child[i]); // Reverse vector (variable sized array) of child // pointers for (int i=0; i<n/2; i++) { Node *temp = root->child[i]; root->child[i] = root->child[n-i-1]; root->child[n-i-1] = temp; }}// Utility function to create a new tree nodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; return temp;}// Prints the n-ary tree level wisevoid printNodeLevelWise(Node * root){ if (root==NULL) return; // Create a queue and enqueue root to it queue<Node *>q; q.push(root); // Do level order traversal. Two loops are used // to make sure that different levels are printed // in different lines while (!q.empty()) { int n = q.size(); while (n>0) { // Dequeue an item from queue and print it Node * p = q.front(); q.pop(); cout << p->key << " "; // Enqueue all childrent of the dequeued item for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); n--; } cout << endl; // Separator between levels }}// Prints the n-ary tree level wisevoid printNodeLevelWise(Node * root){ if (root==NULL) return; // Create a queue and enqueue root to it queue<Node *>q; q.push(root); // Do level order traversal. Two loops are used // to make sure that different levels are printed // in different lines while (!q.empty()) { int n = q.size(); while (n>0) { // Dequeue an item from queue and print it Node * p = q.front(); q.pop(); cout << p->key << " "; // Enqueue all childrent of the dequeued item for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); n--; } cout << endl; // Separator between levels }}http://www.geeksforgeeks.org/longest-path-undirected-tree/
Given an undirected tree, we need to find the longest path of this tree where a path is defined as a sequence of nodes.
This problem is same as diameter of n-ary tree.
Read full article from Mirror of n-ary Tree - GeeksforGeeks