- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find leaf and non-leaf nodes of a binary tree in Python

Suppose we have a binary tree, we have to find a list of two numbers where the first number is the count of leaves in the tree and the second number is the count of non-leaf nodes.

So, if the input is like

then the output will be (3, 2), as there are 3 leaves and 2 non-leaf nodes.

To solve this, we will follow these steps −

- if n is null, then
- return (0, 0)

- if left of n is null and right of n is null, then
- return (1, 0)

- left := solve(left of n)
- right := solve(right of n)
- return (left[0] + right[0], 1 + left[1] + right[1])

Let us see the following implementation to get better understanding −

## Example

class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right class Solution: def solve(self, n): if not n: return 0, 0 if not n.left and not n.right: return 1, 0 left, right = self.solve(n.left), self.solve(n.right) return left[0] + right[0], 1 + left[1] + right[1] ob = Solution() root = TreeNode(6) root.left = TreeNode(2) root.right = TreeNode(6) root.right.left = TreeNode(10) root.right.right = TreeNode(2) print(ob.solve(root))

## Input

root = TreeNode(6) root.left = TreeNode(2) root.right = TreeNode(6) root.right.left = TreeNode(10) root.right.right = TreeNode(2)

## Output

(3, 2)

- Related Questions & Answers
- Count Non-Leaf nodes in a Binary Tree in C++
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- C++ Pairwise Swap Leaf Nodes in a Binary Tree
- Product of all leaf nodes of binary tree in C++
- Find the sum of left leaf nodes of a given Binary Tree in C++
- C++ Program to Find Deepest Left Leaf in a Binary Tree
- Find height of a special binary tree whose leaf nodes are connected in C++
- Program to print the longest leaf to leaf path in a Binary tree using C++
- Maximum sum of non-leaf nodes among all levels of the given binary tree in C++
- Print all leaf nodes of a binary tree from right to left in C++
- Program to find number of good leaf nodes pairs using Python
- Find the closest leaf in a Binary Tree in C++
- Program to find sum of longest sum path from root to leaf of a binary tree in Python
- Python Program to Count Number of Leaf Node in a Tree
- Print All Leaf Nodes of a Binary Tree from left to right using Iterative Approach in C++

Advertisements