Spread the post

Sum of right leaf nodes in binary tree

Write an efficient algorithm to sum of all right leaves nodes of binary tree.

Suppose following nodes are insert in binary tree.

90108077205060 Stack Areamainresult (int) ? root(pointer)nodenew_node(pointer)value (int) =20 Heap Areastruct Treedata (int)= 90left (pointer) right (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 80left (pointer) right (pointer) struct Treedata (int)= 77left (pointer)= NULLright (pointer) struct Treedata (int)= 60left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 50left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 20left (pointer)= NULLright (pointer)= NULL

Output

90108077205060

Output: 110 [50+60].

Program for sum of all right leaf nodes. Time complexity O(n).

Output

View process.

Stack Areamainresult (int) =110root(pointer)right_level_sresult(pointer)temp(pointer)right_level_sresult(pointer)temp(pointer)right_level_sresult(pointer)temp(pointer) Heap Areastruct Treedata (int)= 90left (pointer) right (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 80left (pointer) right (pointer) struct Treedata (int)= 77left (pointer) right (pointer) struct Treedata (int)= 60left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 50left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 20left (pointer)= NULLright (pointer)= NULL

View steps of execution

Submit your solution in comment section.

Spread the post

Recommended Posts: