Graph Traversal using DFS is an obvious way to traverse a tree with recursion. Below is an algorithm for traversing binary tree using DFS.
- Initialize the current node as root node and the parent as -1.
- Traverse the Binary Tree as the in the general DFS fashion and keep of increasing the level of the node as we traverse farther from the root node.
- While traversing we check if the level of the current node of the binary tree is even then add in even sum else add in odd sum.
- Finally, print the Absolute difference of the of even sum and the odd sum.
Absolute difference of sum of odd and even nodes of a binary tree 4
Time Complexity: O(V + E) where V is the vertices and E is the edges.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.