Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Count Non-Leaf Nodes In Binary Tree

Easy Acceptance 60.48% Points 20.00

You are given the root of a binary tree. Your task is to count the number of non-leaf (internal) nodes.

A non-leaf node is a node that has at least one child.

Return the total number of nodes that are not leaf nodes.

Examples
Example 1

image Input: root = [1,2,3,4,5]
Output: 2
Explanation: Nodes 1 and 2 have children; nodes 3, 4, and 5 are leaves. So there are 2 non-leaf nodes.

Example 2

image Input: root = [1]
Output: 0
Explanation: A single node is a leaf, so there are no non-leaf nodes.

Example 3

image Input: root = []
Output: 0
Explanation: An empty tree has no non-leaf nodes.

Constraints
    • 0 = Number of nodes = 104
    • -10? = Node.data = 10?
Companies
Amazon Nutanix PhonePe
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions