Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on.
3 0 / \ / \ 2 5 == >; 1 1 / \ / \ 1 4 2 2
The idea is to traverse tree starting from root. While traversing pass depth of node as parameter. We can track depth by passing it as 0 for root and one-plus-current-depth for children.
Below is the implementation of the idea.
Before Replacing Nodes 1 2 4 3 5 After Replacing Nodes 2 1 2 0 1
This article is contributed by Chhavi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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 every node with depth in N-ary Generic Tree
- Depth of the deepest odd level node in Binary Tree
- Minimum valued node having maximum depth in an N-ary Tree
- Find Minimum Depth of a Binary Tree
- Calculate depth of a full Binary tree from Preorder
- 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
- Replace each node in binary tree with the sum of its inorder predecessor and successor
- Find depth of the deepest odd level leaf node
- Write a Program to Find the Maximum Depth or Height of a Tree
- Depth of an N-Ary tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not