Binary Tree Statistics

You are given a binary tree with n vertices (labeled from 0 to n-1). You are given a 2D array edges where each edge [u, v] represents a directed edge from parent u to child v. The root of the tree is always vertex 0.

Analyze the tree and calculate the following four metrics:

  1. Height: The height of the tree, counted in edges. An empty tree has a height of -1, and a single-node tree has a height of 0.
  2. Total Number of Nodes: The total count of vertices in the tree.
  3. Number of Leaves: The count of nodes that have no children.
  4. Number of Internal Nodes: The count of nodes that have at least one child.

Output Constraints: Print exactly one line containing four space-separated integers in this exact order: height total_nodes leaves internal_nodes.

Note: Please be extremely careful with the output. Do not leave any trailing spaces at the end of the line, and do not print any extra blank lines.

Example 1:

Input:

n = 5
edges = [[0, 1], [0, 2], [1, 3], [1, 4]]

Output:

2 5 3 2

Explanation:

  • The total number of nodes is 5.
  • The height is 2 (the longest path is from 0 -> 1 -> 3 or 0 -> 1 -> 4, which is 2 edges).
  • The leaves are nodes 2, 3, and 4 (3 leaves).
  • The internal nodes are nodes 0 and 1 (2 internal nodes).

Example 2:

Input:

n = 1
edges = []

Output:

0 1 1 0

Explanation:

  • The tree has only 1 node, so total nodes = 1.
  • By definition, a single-node tree has a height of 0.
  • Node 0 is a leaf, so leaves = 1.
  • There are no nodes with children, so internal nodes = 0.

Now Your Turn!

Pick the correct output for the given input

Input:

n = 4
edges = [[0, 1], [1, 2], [2, 3]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= n <= 104
  • edges.length == max(0, n - 1)
  • edges[i].length == 2
  • 0 <= edges[i][0], edges[i][1] < n
  • A node has at most 2 children (it is a valid binary tree).
  • Vertex 0 is always the root.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
void analyzeTree(int n, vector<vector<int>>& edges) {
// Write your code here
}
};
Test Case

Input:

Edges
N