Sum of leaf nodes in BST
Submissions: 8438   Accuracy:


  Difficulty: Easy   Marks: 2

Given a Binary Search Tree, find the sum of all leaf nodes. BST has the following property (duplicate nodes are possible):

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.

The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case consists of integer N, denoting the number of elements in the BST. The second line of each test case consists of N space-separated integers denoting the elements in the BST.

For each testcase, in a new line, print the sum of leaf nodes.

Your Task:
This is a function problem. You don't have to take any input. You are required to complete the function sumOfLeafNodes that takes root as parameter and returns the sum of leaf nodes. 

1 <= T <= 103     
1 <= N <= 105

67 34 82 12 45 78


In first test case, the BST for the given input will be-


          /             \

   34                  82

  /    \                /

12   45         78

Hence, the required sum= 12 + 45 + 78 = 135

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Sajal Agrawal
Author: sajalagrawal

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Need help with your code? Please use, generate link and share the link here.

to report an issue on this page.