700690. Count Non-Leaf Nodes in Tree

Basic

Count Non-Leaf Nodes in Tree

Slug: count-non-leaf-nodes-in-tree Difficulty: Basic Id: 700690 Topic Tags: Tree, Data Structures Company Tags: None

Summary

Given a tree data structure, count the number of non-leaf nodes. A leaf node is defined as a node with no children. This problem involves traversing and manipulating the tree data structure, making it relevant to the "Tree" topic tag.

Detailed Explanation

To solve this problem, we can use a depth-first search (DFS) traversal approach. The key idea is to keep track of the current node's children and recursively traverse the subtree rooted at each child if the current node has more than one child. This ensures that we only count nodes with multiple children as non-leaf nodes.

Here's the step-by-step breakdown:

  1. Start by initializing a counter for non-leaf nodes (let's call it nonLeafCount).
  2. Define a recursive function countNonLeafNodes(node) to perform the DFS traversal.
  3. In the countNonLeafNodes function, check if the current node is not a leaf node (i.e., has more than one child). If so, increment the nonLeafCount.
  4. Recursively call countNonLeafNodes on each child of the current node (if it has multiple children).
  5. Return the final count of non-leaf nodes.

Here's an ASCII art diagram illustrating the tree structure:

        1
       / \
      2   3
     / \   \
    4   5   6

In this example, the non-leaf nodes are 1 and 2 (since they have multiple children).

Time complexity: O(n), where n is the number of nodes in the tree. We visit each node once. Space complexity: O(h), where h is the height of the tree. This is because we need to store the recursive call stack, which grows up to the height of the tree.

Optimized Solutions

Java

View on GeeksforGeeks
public int countNonLeafNodes(Node root) {
    if (root == null || (root.left == null && root.right == null)) return 0;
    if (root.left != null && root.right != null) return 1 + countNonLeafNodes(root.left) + countNonLeafNodes(root.right);
    return 0;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.