![]() |
Given a binary tree, We have to find the sum of all leaf nodes. A leaf node is a node that does not have any children. Example: Input binary tree: Table of Content Using recursive approachIn this approach, we define a recursive function sumOfLeafNodesRecursive that traverses the binary tree recursively. It calculates the sum of leaf nodes by recursively summing leaf node values starting from a given node. If the input node is a leaf node, its value is returned; otherwise, the function recursively calculates the sum of leaf nodes for its left and right children. Approach:
Example: This example uses recursive approach to calculates the sum of leaf node in binary tree.
Output 12 Time complexity: O(n), where h is the height of the tree. Space complexity: O(h), where n is the number of nodes in the tree. Iterative Approach Using StackThis approach employs an iterative depth-first traversal of the binary tree using a stack. Starting with the root node, it iterates while there are nodes in the stack. At each iteration, it pops a node from the stack and checks if it is a leaf node. If it is, its value is added to the sum. If it’s not a leaf node, its children are pushed onto the stack. Approach:
Example: This example uses Iterative approach to calculates the sum of leaf node in binary tree.
Output 12 Time complexity: O(n), where h is the height of the tree. Space complexity: O(h), where n is the number of nodes in the tree. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |