700690. Count Non-Leaf Nodes in Tree
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:
- Start by initializing a counter for non-leaf nodes (let's call it
nonLeafCount). - Define a recursive function
countNonLeafNodes(node)to perform the DFS traversal. - In the
countNonLeafNodesfunction, check if the current node is not a leaf node (i.e., has more than one child). If so, increment thenonLeafCount. - Recursively call
countNonLeafNodeson each child of the current node (if it has multiple children). - 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
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;
}