Array Representation: The N-ary tree is serialized in the array arr using level order traversal as described below:
- The input is given as a level order traversal of N-ary Tree.
- The first element of the array arr is the root node.
- Then, followed by a number N, which denotes the number of children of the previous node. Value zero denotes Null Node.
- Traverse the tree starting from root.
- While traversing pass depth of node as a parameter.
- Track depth by passing it as 0 for root and (1 + currrent level) for children.
Below is the implementation of the above approach:
0 1 1 1 2 2
Time Complexity: O(N), where N is the number of nodes in Tree.
Auxiliary Space: O(N), where N is the number of nodes in Tree.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Replace node with depth in a binary tree
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Depth of the deepest odd level node in Binary Tree
- Minimum valued node having maximum depth in an N-ary Tree
- Height of a generic tree from parent array
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Find depth of the deepest odd level leaf node
- Write a Program to Find the Maximum Depth or Height of a Tree
- Find Minimum Depth of a Binary Tree
- Calculate depth of a full Binary tree from Preorder
- Depth of an N-Ary tree
- Sum of nodes at maximum depth of a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Set 2
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Generic Trees(N-array Trees)
- Replace each node in binary tree with the sum of its inorder predecessor and successor
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Find root of the tree where children id sum for every node is given
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.