Spread the post

Sum of all leaf nodes of binary tree

Find the sum of leaf nodes that are exist in binary tree without using recursion.

For example given Binary tree are contain following nodes.

13762485910

Result

Sum of leaf nodes is : 31

Function to find the sum of all nodes of binary tree. use queue to solve this problem.

View leaf nodes.

13762485910

Sum is [10+9+6+7]=31

View pointers and nodes of linked list before reverse.

Stack Areamainhead(pointer) NULLroot(pointer)tail(pointer) NULL Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 2left (pointer) right (pointer) struct Treedata (int)= 3left (pointer) right (pointer) struct Treedata (int)= 4left (pointer) right (pointer)= NULLstruct Treedata (int)= 5left (pointer) right (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 9left (pointer)= NULLright (pointer) struct Treedata (int)= 6left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULL

Try it Yourself

program to find the sum of all nodes of binary tree. without recursion.


Output

View process

Stack Areamainhead(pointer)root(pointer)tail(pointer)sum_of_leafsum (int) =31temp(pointer) Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 2left (pointer) right (pointer) struct Treedata (int)= 3left (pointer) right (pointer) struct Treedata (int)= 4left (pointer) right (pointer)= NULLstruct Treedata (int)= 5left (pointer) right (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 9left (pointer)= NULLright (pointer) struct Treedata (int)= 6left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer) struct Queuelink (pointer) next (pointer)= NULL

Try it Yourself

Spread the post

Recommended Posts: